--- /dev/null
+{
+ "release_user": "kwrobot.release.vtk",
+ "project": "vtk/vtk",
+ "maintainers": [
+ "ben.boeckel",
+ "ken-martin",
+ "utkarsh.ayachit",
+ "vbolea"
+ ]
+}
# Suppress ThirdParty source code from displaying warnings.
"[Tt]hird[Pp]arty"
+ # clang will often give multiline warnings from macro expansions,
+ # where the first part has "warning:" and subsequent parts have "note:"
+ # and those will sometimes expand into systems headers. When this occurs
+ # for ThirdParty code, we want it suppressed too. Do so here for headers within Xcode.
+ "Xcode\\.app/Contents/Developer.+note:"
+
# Suppress Remote module source code from displaying warnings.
# Suppress modules individually as just "Remote" is a common pattern
"[Rr]emote.[Mm]oment[Ii]nvariants"
features = python_code_features
features.update(vtk_features.FEATURES)
+extra_packages = []
+if 'web' in vtk_features.FEATURES:
+ extra_packages.append('vtkmodules.web')
+
+########################################
+# Version computation logic
+########################################
+
+# Assume a development version at first.
+version_base = '@VTK_MAJOR_VERSION@.@VTK_MINOR_VERSION@.@VTK_BUILD_VERSION@'
+version = version_base + '.dev0'
+
+if 'GITLAB_CI' in os.environ:
+ if 'CI_COMMIT_TAG' in os.environ:
+ if '.rc' in os.environ['CI_COMMIT_TAG']:
+ # rc tag. Add this to the version.
+ rc_bit = os.environ['CI_COMMIT_TAG'].split('.')[-1]
+ version = version_base + '.' + rc_bit
+ else:
+ # Official release, use the version number.
+ version = version_base
+ elif 'CI_COMMIT_BRANCH' in os.environ:
+ # Build on an official branch.
+
+ # Check if we're on `master` or the release branch.
+ if 20200000 < int('@VTK_BUILD_VERSION@'):
+ # Master, count commits since the last nightly update.
+ git_log = subprocess.Popen([
+ 'git',
+ 'log',
+ '--first-parent',
+ '--pretty=%s',
+ os.environ['CI_COMMIT_BRANCH'],
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ cwd=os.environ['GIT_CLONE_PATH'],
+ )
+
+ count = 0
+ for line in git_log.stdout.readlines():
+ if line == b'VTK Nightly Date Stamp\n':
+ break
+ count += 1
+ else:
+ # Release branch, count commits since the last tag.
+ git_log = subprocess.Popen([
+ 'git',
+ 'log',
+ '--first-parent',
+ '--pretty=%s',
+ 'v' + version_base + '..'
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ cwd=os.environ['GIT_CLONE_PATH'],
+ )
+
+ count = len(git_log.stdout.readlines())
+
+ version = version_base + '.dev' + str(count)
+ elif 'CI_MERGE_REQUEST_ID' in os.environ:
+ # Build on a merge request.
+ version = version_base + '.dev0' + '+mr' + \
+ os.environ['CI_MERGE_REQUEST_ID']
+
setup(
name='vtk',
- version='@VTK_MAJOR_VERSION@.@VTK_MINOR_VERSION@.@VTK_BUILD_VERSION@',
+ version=version,
author='VTK developers',
packages=[
'vtkmodules',
'vtkmodules.tk',
'vtkmodules.util',
'vtkmodules.wx',
- ],
+ ] + extra_packages,
py_modules=[
'vtk',
],
ext_package='vtkmodules',
ext_modules=[
- # https://gitlab.kitware.com/cmake/cmake/issues/19145
+ # https://gitlab.kitware.com/cmake/cmake/-/issues/19145
#ConfiguredCMakeExtension('vtkmodules', target='vtkpythonmodules'),
ConfiguredCMakeExtension('vtkCommonCorePython', target='vtkCommonCorePython'),
],
# macOS modules.
'*-darwin.so',
# macOS shared libraries.
- 'lib*.dylib*',
+ '.dylibs',
# Windows modules.
'*.pyd',
# Windows shared libraries.
# VTK version number components.
set(VTK_MAJOR_VERSION 9)
set(VTK_MINOR_VERSION 0)
-set(VTK_BUILD_VERSION 1)
+set(VTK_BUILD_VERSION 3)
if (NOT VTK_MINOR_VERSION LESS 100)
message(FATAL_ERROR
set(vtk_features)
+if (TARGET VTK::WebPython)
+ list(APPEND vtk_features "web")
+endif ()
+
if (TARGET VTK::mpi)
list(APPEND vtk_features "mpi")
endif ()
# Force some VTK options for wheels.
set(VTK_PYTHON_VERSION 3)
set(VTK_BUILD_TESTING OFF)
+set(VTK_LEGACY_SILENT ON)
set(VTK_ENABLE_WRAPPING ON)
set(VTK_WRAP_PYTHON ON)
set(Python3_ARTIFACTS_INTERACTIVE ON)
set(setup_py_build_dir
"build/lib.${python_platform}-${Python3_VERSION_MAJOR}.${Python3_VERSION_MINOR}")
# Required for Windows DLL placement.
-set(CMAKE_INSTALL_BINDIR
- # Must correlate with `vtk_module_wrap_python(PYTHON_PACKAGE)` argument
- "${setup_py_build_dir}/vtkmodules")
-set(CMAKE_INSTALL_LIBDIR
- # Must correlate with `vtk_module_wrap_python(PYTHON_PACKAGE)` argument
- "${setup_py_build_dir}/vtkmodules")
+if (WIN32)
+ set(CMAKE_INSTALL_BINDIR
+ # Must correlate with `vtk_module_wrap_python(PYTHON_PACKAGE)` argument
+ "${setup_py_build_dir}/vtkmodules")
+elseif (APPLE)
+ set(CMAKE_INSTALL_LIBDIR
+ # Store libraries in a subdirectory here.
+ "${setup_py_build_dir}/vtkmodules/.dylibs")
+else ()
+ set(CMAKE_INSTALL_LIBDIR
+ # Linux bundles what libraries we have when they're put beside the modules.
+ "${setup_py_build_dir}/vtkmodules")
+endif ()
set(VTK_PYTHON_SITE_PACKAGES_SUFFIX ".")
set(VTK_CUSTOM_LIBRARY_SUFFIX "")
set(VTK_INSTALL_SDK OFF)
cmake_minimum_required(VERSION 3.8...3.12 FATAL_ERROR)
foreach(policy
CMP0083 # CMake 3.14
+ CMP0077 # CMake 3.13
CMP0071 # CMake 3.10
CMP0068 # CMake 3.9
)
#-----------------------------------------------------------------------------
# Add the Remote Subdirectory
-add_subdirectory(Remote)
+if (VTK_ENABLE_REMOTE_MODULES)
+ add_subdirectory(Remote)
+endif ()
#-----------------------------------------------------------------------------
# Does VTK require support for 64 bit file systems
endif ()
endif ()
+set(vtk_library_version_info
+ VERSION "${VTK_VERSION}"
+ SOVERSION "1")
+if (VTK_WHEEL_BUILD)
+ set(vtk_library_version_info)
+endif ()
+
vtk_module_build(
MODULES ${vtk_modules}
KITS ${vtk_kits}
CMAKE_DESTINATION "${vtk_cmake_destination}"
LICENSE_DESTINATION "${CMAKE_INSTALL_LICENSEDIR}"
LIBRARY_NAME_SUFFIX "${VTK_CUSTOM_LIBRARY_SUFFIX}"
- VERSION "${VTK_VERSION}"
- SOVERSION "1"
+ ${vtk_library_version_info}
TEST_DATA_TARGET VTKData
INSTALL_HEADERS "${VTK_INSTALL_SDK}"
BUILD_WITH_KITS "${VTK_ENABLE_KITS}"
"${vtk_required_python_modules}\n")
get_property(vtk_soabi GLOBAL
PROPERTY _vtk_python_soabi)
+
+ if (APPLE AND VTK_WHEEL_BUILD)
+ list(APPEND CMAKE_INSTALL_RPATH
+ # Wheels place loaded libraries under a `.dylibs` subdirectory. Add this
+ # to the rpath list.
+ "@loader_path/.dylibs")
+ endif ()
+
vtk_module_wrap_python(
MODULES ${vtk_modules}
INSTALL_EXPORT VTKPython
WRAPPED_MODULES vtk_python_wrapped_modules
TARGET VTK::vtkpythonmodules)
+ if (APPLE AND VTK_WHEEL_BUILD)
+ list(REMOVE_ITEM CMAKE_INSTALL_RPATH
+ "@loader_path/.dylibs")
+ endif ()
+
add_subdirectory(Wrapping/Python)
export(
ExampleDataArrayRangeAPI.cxx
ExampleDataArrayRangeDispatch.cxx
UnitTestMath.cxx
+ TestAbstractArraySize.cxx
TestArrayAPI.cxx
TestArrayAPIConvenience.cxx
TestArrayAPIDense.cxx
--- /dev/null
+/*=========================================================================
+
+ Program: Visualization Toolkit
+ Module: TestAbstractArraySize.cxx
+
+ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
+ All rights reserved.
+ See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
+
+ This software is distributed WITHOUT ANY WARRANTY; without even
+ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the above copyright notice for more information.
+
+=========================================================================*/
+
+#include <vtkDoubleArray.h>
+#include <vtkNew.h>
+#include <vtkStringArray.h>
+
+#include <iostream>
+#include <sstream>
+#include <stdexcept>
+
+int TestAbstractArraySize(int vtkNotUsed(argc), char* vtkNotUsed(argv)[])
+{
+ int status = 0;
+ vtkNew<vtkStringArray> stringArray;
+ stringArray->SetNumberOfComponents(2);
+ stringArray->SetNumberOfTuples(1);
+ std::cout << "Size is now " << stringArray->GetSize() << "\n";
+ if (stringArray->GetMaxId() < 1)
+ {
+ std::cerr << "Allocation failed: number of tuples requested not provided.\n";
+ status = 1;
+ }
+ // Test for regression
+ stringArray->SetValue(0, "This value is OK.");
+ stringArray->SetValue(1, "This used to crash, even though GetMaxId reported a proper size.");
+
+ // Test for desired behavior
+ stringArray->SetNumberOfValues(3);
+ std::cout << "Size is now " << stringArray->GetSize() << "\n";
+ if (stringArray->GetSize() < 4)
+ {
+ std::cerr
+ << "Allocation failed: SetNumberOfValues should always allocate to a tuple boundary.\n";
+ status = 1;
+ }
+ // Same as above, but test a vtkDataArray subclass.
+ vtkNew<vtkDoubleArray> doubleArray;
+ doubleArray->SetNumberOfComponents(3);
+ doubleArray->SetNumberOfValues(7);
+ if (doubleArray->GetSize() != 9)
+ {
+ std::cerr
+ << "Allocation failed: SetNumberOfValues should always allocate to a tuple boundary.\n";
+ status = 1;
+ }
+
+ return status;
+}
//----------------------------------------------------------------------------
bool vtkAbstractArray::SetNumberOfValues(vtkIdType numValues)
{
- vtkIdType numTuples = this->NumberOfComponents == 1
- ? numValues
- : (numValues + this->NumberOfComponents - 1) / this->NumberOfComponents;
+ vtkIdType numTuples = numValues / this->NumberOfComponents;
+ if (numValues % this->NumberOfComponents)
+ {
+ ++numTuples;
+ }
if (!this->Resize(numTuples))
{
return false;
return this->name; \
}
+//
+// Set 'enum class' type. Creates member Set"name"() (e.g., SetKind());
+// vtkSetMacro can't be used because 'enum class' won't trivially convert to integer for logging.
+//
+#define vtkSetEnumMacro(name, enumType) \
+ virtual void Set##name(enumType _arg) \
+ { \
+ vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting " #name " to " \
+ << static_cast<std::underlying_type<enumType>::type>(_arg)); \
+ if (this->name != _arg) \
+ { \
+ this->name = _arg; \
+ this->Modified(); \
+ } \
+ }
+
+//
+// Get 'enum class' type. Creates member Get"name"() (e.g., GetKind());
+// vtkSetMacro can't be used because 'enum class' won't trivially convert to integer for logging.
+//
+#define vtkGetEnumMacro(name, enumType) \
+ virtual enumType Get##name() const \
+ { \
+ vtkDebugMacro(<< this->GetClassName() << " (" << this << "): returning " << #name " of " \
+ << static_cast<std::underlying_type<enumType>::type>(this->name)); \
+ return this->name; \
+ }
+
//
// Set character string. Creates member Set"name"()
// (e.g., SetFilename(char *));
vtkTypeBool vtkStringArray::Resize(vtkIdType sz)
{
vtkStdString* newArray;
- vtkIdType newSize = sz;
+ vtkIdType newSize = sz * this->NumberOfComponents;
if (newSize == this->Size)
{
--- /dev/null
+# 9.0.0
+
+See [Discourse](https://discourse.vtk.org/t/vtk-9-0-0/3205) for release notes.
+
+# 9.0.2
+
+VTK 9.0.2 collects fixes to 9.0.1 which have been made since its release. Of
+particular interest are the fixes to macOS rendering, support for the macOS
+arm64 platform, and updates for API changes in external libraries.
+
+# New classes
+
+ - Added a `vtkImageProbeFilter` which works like `vtkProbeFilter`, but for
+ `vtkImageData`
+
+# New support
+
+ - `enum class` setters and getters are now supported via
+ `vtk{Get,Set}EnumMacro`
+
+# Fixes
+
+ - The `QVTKRenderWidget.h` is now installed.
+ - `vtk3DLinearGridPlaneCutter` guards against `nullptr` points and cells
+ - The composite date mapper now iterates over data blocks properly
+ - `vtkStringArray::Resize` takes tuple elements into account
+ - `vtkArrowSource` now supports scalong and rotation around the origin or the
+ arrow's center point
+ - The `VTK::DomainsChemistryOpenGL2`, `VTK::RenderingContextOpenGL2`, and
+ `VTK::RenderingOpenGL2` modules are added to the `Rendering` group to avoid
+ missing implementations of rendering components
+ - `vtkCutter` enables point merging when requested through a
+ `vtkPointLocator` which merges points
+ - `vtkAxesActor` bounds calculations improved to avoid assumptions about
+ range values
+ - `vtkWindowLevelLookupTable` out-of-range colors are now initialized
+ properly
+ - `vtkImageReslice::RequestInformation` is refactored handle common image
+ information passing
+ - `vtkImageReslice` creates a new interpolator in `::GetInterpolator`; this
+ new interpolator now uses the same interpolation mode as `vtkImageReslice`
+ itself
+
+## macOS
+
+ - macOS wheels are now built and uploaded by VTK's CI
+ - Fixes for macOS OpenGL state tracking (related to `GL_SCISSOR`)
+ - Multisampling on macOS with Intel graphics turned off for volume rendering
+ - OpenGL state tracking on macOS with layers is improved (rather than using
+ the wrong context between layers)
+ - OSPRay is disabled when running under macOS Rosetta
+
+## Third Party
+
+ - HDF5 has been updated to address errors on newer Xcode compilers
+ - HDF5 macOS universal2 compilation fixes
+ - `VTK::mpi` now disables C++ bindings for SGI MPT as well
+ - Usage of `numpy.character` is removed (deprecated in NumPy 1.19)
+ - Avoidance of APIs deprecated in Python 3.9
+ - Compilation with newer libfreetype resolved (`FT_CALLBACK_DEF` usage
+ removed)
+
+# 9.0.3
+
+A minor patchset on top of 9.0.2 to fix problems with the new release process'
+configuration when building the wheels.
+
+## Wheels
+
+ - Disable `VTK_DEBUG_LEAKS` in wheel builds
+ - Remove long-deprecated API usage in the Python bindings
+++ /dev/null
-# node-numbering-change-for-VTK_LAGRANGE_HEXAHEDRON
-
-The node numbering for VTK_LAGRANGE_HEXAHEDRON has been corrected,
-to match the numbering of VTK_QUADRATIC_HEXAHEDRON when the Lagrange
-cell is quadratic.
-The change consists in inverting the node numbering on the edge (x=0, y=1)
-with the edge (x=1, y=1), has shown below for a quadratic cell.
-
-
- quadratic VTK_QUADRATIC_HEXAHEDRON
-VTK_LAGRANGE_HEXAHEDRON VTK_LAGRANGE_HEXAHEDRON
- before VTK 9.0 after VTK 9.0
-
- +_____+_____+ +_____+_____+
- |\ :\ |\ :\
- | + : + | + : +
- | \ 19 + \ | \ 18 + \
- 18 + +-----+-----+ 19 + +-----+-----+
- | | : | | | : |
- |__ | _+____: | |__ | _+____: |
- \ + \ + \ + \ +
- + | + | + | + |
- \ | \| \ | \|
- +_____+_____+ +_____+_____+
-
-In order to maintain the compatibility, the readers can convert internally
-existing files to the new numbering. To this end, The XML file version has been
-bumped from 2.1 to 2.2 and the legacy file version has been bumped from 5.0 to 5.1.
+++ /dev/null
-# pegtl
-
-VTK can now be built against an external PEGTL library.
vtkDomainsChemistryOpenGL2
DESCRIPTION
OpenGL support for chemistry data
+GROUPS
+ Rendering
IMPLEMENTS
VTK::DomainsChemistry
DEPENDS
vtkCocoaRenderWindow* renderWindow = [customView renderWindow];
if (renderWindow && renderWindow->GetMapped())
{
- renderWindow->InitializeFromCurrentContext();
+ bool contextInitialised = renderWindow->Superclass::InitializeFromCurrentContext();
+ assert(contextInitialised);
+ (void)contextInitialised;
renderWindow->Render();
}
BasicVTKView* thisView = [self leftView];
// Explicitly enable HiDPI/Retina (this is the default anyway).
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[thisView setWantsBestResolutionOpenGLSurface:YES];
+#pragma clang diagnostic pop
[thisView initializeVTKSupport];
// Explicitly disable HiDPI/Retina as a demonstration of the difference.
// One might want to disable it to reduce memory usage / increase performance.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[thisView setWantsBestResolutionOpenGLSurface:NO];
+#pragma clang diagnostic pop
[thisView initializeVTKSupport];
// Explicitly enable HiDPI/Retina (this is required when using CAOpenGLLayer, otherwise the view
// will be 1/4 size on Retina).
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[thisView setWantsBestResolutionOpenGLSurface:YES];
+#pragma clang diagnostic pop
[thisView initializeVTKSupport];
[thisView initializeLayerSupport];
vtkUnstructuredGrid* input, vtkPlane* plane, vtkPolyData* output)
{
// Make sure there is input data to process
+ if (!input || !plane || !output)
+ {
+ vtkLog(INFO, "Null input, plane, or output");
+ return 1;
+ }
+
vtkPoints* inPts = input->GetPoints();
- vtkIdType numPts = inPts->GetNumberOfPoints();
+ vtkIdType numPts = inPts ? inPts->GetNumberOfPoints() : 0;
vtkCellArray* cells = input->GetCells();
- vtkIdType numCells = cells->GetNumberOfCells();
+ vtkIdType numCells = cells ? cells->GetNumberOfCells() : 0;
if (numPts <= 0 || numCells <= 0)
{
vtkLog(INFO, "Empty input");
- return 0;
+ return 1;
}
// Check the input point type. Only real types are supported.
newPlane->Push(-d + this->GetValue(0));
linear3DCutter->SetPlane(newPlane);
+ bool mergePoints =
+ this->GetLocator() && !this->GetLocator()->IsA("vtkNonMergingPointLocator");
+ linear3DCutter->SetMergePoints(mergePoints);
linear3DCutter->SetOutputPointsPrecision(this->GetOutputPointsPrecision());
linear3DCutter->SetInputArrayToProcess(0, this->GetInputArrayInformation(0));
vtkNew<vtkEventForwarderCommand> progressForwarder;
vtk_add_test_cxx(vtkFiltersSourcesCxxTests tests
TestArcSource.cxx,NO_VALID
+ TestArrowSource.cxx
TestCapsuleSource.cxx,NO_VALID
TestCellTypeSource.cxx,NO_VALID
TestConeSource.cxx,NO_VALID
--- /dev/null
+/*=========================================================================
+
+ Program: Visualization Toolkit
+ Module: TestArrowSource.cxx
+
+ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
+ All rights reserved.
+ See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
+
+ This software is distributed WITHOUT ANY WARRANTY; without even
+ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the above copyright notice for more information.
+
+=========================================================================*/
+
+#include <vtkRegressionTestImage.h>
+#include <vtkTestUtilities.h>
+
+#include <vtkActor.h>
+#include <vtkArrowSource.h>
+#include <vtkCamera.h>
+#include <vtkCompositeDataPipeline.h>
+#include <vtkExecutive.h>
+#include <vtkExtractGrid.h>
+#include <vtkInformationVector.h>
+#include <vtkMultiBlockDataSet.h>
+#include <vtkMultiBlockPLOT3DReader.h>
+#include <vtkPolyDataMapper.h>
+#include <vtkPolyDataReader.h>
+#include <vtkProperty.h>
+#include <vtkRenderWindow.h>
+#include <vtkRenderWindowInteractor.h>
+#include <vtkRenderer.h>
+
+int TestArrowSource(int argc, char* argv[])
+{
+ vtkSmartPointer<vtkArrowSource> arrow = vtkSmartPointer<vtkArrowSource>::New();
+ vtkSmartPointer<vtkArrowSource> arrowCentral = vtkSmartPointer<vtkArrowSource>::New();
+ vtkSmartPointer<vtkArrowSource> arrowInvertCentral = vtkSmartPointer<vtkArrowSource>::New();
+
+ double shaftRadius = arrow->GetShaftRadius();
+ arrow->SetShaftRadius(shaftRadius * 2.0);
+ arrowCentral->SetShaftRadius(shaftRadius * 2.0);
+ arrowInvertCentral->SetShaftRadius(shaftRadius * 2.0);
+
+ double shaftRes = arrow->GetShaftResolution();
+ arrow->SetShaftResolution(shaftRes * 15.0);
+ arrowCentral->SetShaftResolution(shaftRes * 15.0);
+ arrowInvertCentral->SetShaftResolution(shaftRes * 15.0);
+
+ double tipRes = arrow->GetTipResolution();
+ arrow->SetTipResolution(tipRes * 10.0);
+ arrowCentral->SetTipResolution(tipRes * 10.0);
+ arrowInvertCentral->SetTipResolution(tipRes * 10.0);
+
+ // Centralize just these arrows
+ arrowCentral->SetArrowOriginToCenter();
+ arrowInvertCentral->SetArrowOriginToCenter();
+
+ // Invert only this arrow
+ arrowInvertCentral->InvertOn();
+
+ arrow->Update();
+ arrowCentral->Update();
+ arrowInvertCentral->Update();
+
+ vtkSmartPointer<vtkPolyData> polydata = arrow->GetOutput();
+ vtkSmartPointer<vtkPolyData> polydataCentral = arrowCentral->GetOutput();
+ vtkSmartPointer<vtkPolyData> polydataInvertCentral = arrowInvertCentral->GetOutput();
+
+ vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
+ vtkSmartPointer<vtkPolyDataMapper> mapperCentral = vtkSmartPointer<vtkPolyDataMapper>::New();
+ vtkSmartPointer<vtkPolyDataMapper> mapperInvertCentral =
+ vtkSmartPointer<vtkPolyDataMapper>::New();
+
+ mapper->SetInputData(polydata);
+ mapper->ScalarVisibilityOff();
+
+ mapperCentral->SetInputData(polydataCentral);
+ mapperCentral->ScalarVisibilityOff();
+
+ mapperInvertCentral->SetInputData(polydataInvertCentral);
+ mapperInvertCentral->ScalarVisibilityOff();
+
+ // Normal Arrow
+ vtkActor* actor = vtkActor::New();
+ actor->SetMapper(mapper);
+ actor->SetPosition(0.0, 0.325, 0.0);
+
+ vtkProperty* propertyToSet = actor->GetProperty();
+ propertyToSet->SetDiffuseColor(0.501, 1.0, 0.0);
+ propertyToSet->SetSpecular(0.15);
+ propertyToSet->SetSpecularPower(5.0);
+
+ // Centralized Arrow
+ vtkActor* actorCentral = vtkActor::New();
+ actorCentral->SetMapper(mapperCentral);
+ actorCentral->SetPosition(0.0, 0.0, 0.0);
+
+ vtkProperty* propertyToSetCentral = actorCentral->GetProperty();
+ propertyToSetCentral->SetDiffuseColor(1.0, 0.647, 0.0);
+ propertyToSetCentral->SetSpecular(0.15);
+ propertyToSetCentral->SetSpecularPower(5.0);
+
+ // Inverted - Centralized Arrow
+ vtkActor* actorInvertCentral = vtkActor::New();
+ actorInvertCentral->SetMapper(mapperInvertCentral);
+ actorInvertCentral->SetPosition(0.0, -0.325, 0.0);
+
+ vtkProperty* propertyToSetInvertCentral = actorInvertCentral->GetProperty();
+ propertyToSetInvertCentral->SetDiffuseColor(0.2, 0.8, 1.0);
+ propertyToSetInvertCentral->SetSpecular(0.25);
+ propertyToSetInvertCentral->SetSpecularPower(5.0);
+
+ // Setup renderer.
+ vtkRenderer* ren = vtkRenderer::New();
+ vtkRenderWindow* win = vtkRenderWindow::New();
+ win->SetMultiSamples(0); // make sure regression images are the same on all platforms
+ win->AddRenderer(ren);
+ ren->Delete();
+ vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
+ iren->SetRenderWindow(win);
+ win->Delete();
+
+ // Add all arrow actors for display.
+ ren->AddActor(actor);
+ ren->AddActor(actorCentral);
+ ren->AddActor(actorInvertCentral);
+
+ // cleanup.
+ actor->Delete();
+ actorCentral->Delete();
+ actorInvertCentral->Delete();
+
+ ren->SetBackground(0.0, 0.0, 0.0);
+ win->SetSize(450, 450);
+
+ vtkCamera* cam = ren->GetActiveCamera();
+ cam->SetPosition(-2.3332, 1.0, 2.25);
+
+ int retVal = vtkRegressionTestImage(win);
+ if (retVal == vtkRegressionTester::DO_INTERACTOR)
+ {
+ iren->Start();
+ }
+ iren->Delete();
+
+ return !retVal;
+}
--- /dev/null
+c56092b0815e27a8fd60770064c8ac696063d20e7580d4b3ada043547f290c9883274f299dcf38fc9be6bab01019c2b2c486fd01638543d8837a098956ee39b5
vtkStandardNewMacro(vtkArrowSource);
+//------------------------------------------------------------------------------
vtkArrowSource::vtkArrowSource()
{
this->TipResolution = 6;
this->ShaftResolution = 6;
this->ShaftRadius = 0.03;
this->Invert = false;
+ this->ArrowOrigin = ArrowOrigins::Default;
this->SetNumberOfInputPorts(0);
}
+//------------------------------------------------------------------------------
int vtkArrowSource::RequestInformation(
vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
return Superclass::RequestInformation(request, inputVector, outputVector);
}
+//------------------------------------------------------------------------------
int vtkArrowSource::RequestData(vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector)
{
tf2->SetTransform(trans2);
tf2->SetInputConnection(append->GetOutputPort());
+ // used only when this->ArrowOrigin is Center (we aim to orient and scale from the centre).
+ vtkTransform* trans3 = vtkTransform::New();
+ vtkTransformFilter* tf3 = vtkTransformFilter::New();
+ trans3->Translate(-0.5, 0.0, 0.0);
+ tf3->SetTransform(trans3);
+
if (piece == 0 && numPieces > 0)
{
if (this->Invert)
{
- tf2->Update();
- output->ShallowCopy(tf2->GetOutput());
+ if (this->ArrowOrigin == ArrowOrigins::Center)
+ {
+ tf3->SetInputConnection(tf2->GetOutputPort());
+ tf3->Update();
+ output->ShallowCopy(tf3->GetOutput());
+ }
+ else
+ {
+ tf2->Update();
+ output->ShallowCopy(tf2->GetOutput());
+ }
}
else
{
- append->Update();
- output->ShallowCopy(append->GetOutput());
+ if (this->ArrowOrigin == ArrowOrigins::Center)
+ {
+ tf3->SetInputConnection(append->GetOutputPort());
+ tf3->Update();
+ output->ShallowCopy(tf3->GetOutput());
+ }
+ else
+ {
+ append->Update();
+ output->ShallowCopy(append->GetOutput());
+ }
}
}
append->Delete();
tf2->Delete();
trans2->Delete();
+ tf3->Delete();
+ trans3->Delete();
return 1;
}
+//------------------------------------------------------------------------------
+std::string vtkArrowSource::GetArrowOriginAsString() const
+{
+ switch (this->ArrowOrigin)
+ {
+ case ArrowOrigins::Default:
+ return "Default";
+ case ArrowOrigins::Center:
+ return "Center";
+ }
+ return "Invalid";
+}
+
+//------------------------------------------------------------------------------
void vtkArrowSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ShaftRadius: " << this->ShaftRadius << "\n";
os << indent << "Invert: " << this->Invert << "\n";
+ os << indent << "Arrow Origin: " << this->GetArrowOriginAsString() << endl;
}
vtkGetMacro(Invert, bool);
//@}
+ enum class ArrowOrigins
+ {
+ Default = 0,
+ Center = 1
+ };
+
+ //@{
+ /**
+ * Sets and Gets the location used for orienting and scaling the arrow.
+ * Default is set to Default.
+ */
+ vtkSetEnumMacro(ArrowOrigin, ArrowOrigins);
+ vtkGetEnumMacro(ArrowOrigin, ArrowOrigins);
+ //@}
+
+ void SetArrowOriginToDefault() { this->SetArrowOrigin(ArrowOrigins::Default); }
+ void SetArrowOriginToCenter() { this->SetArrowOrigin(ArrowOrigins::Center); }
+ std::string GetArrowOriginAsString() const;
+
protected:
vtkArrowSource();
~vtkArrowSource() override {}
int ShaftResolution;
double ShaftRadius;
bool Invert;
+ ArrowOrigins ArrowOrigin;
private:
vtkArrowSource(const vtkArrowSource&) = delete;
static const char* OperationNames[] = {
"None",
"Determinant",
- "Eigenvalue"
+ "Eigenvalue",
"Eigenvector",
"Inverse",
};
endif ()
set(headers
+ QVTKRenderWidget.h
QVTKWin32Header.h)
set(private_headers
set(classes
+ vtkImageProbeFilter
vtkAbstractImageInterpolator
vtkExtractVOI
vtkImageAppendComponents
ImageWeightedSum.cxx,NO_VALID
ImportExport.cxx,NO_VALID
TestBSplineWarp.cxx
+ TestImageProbeFilter.cxx
TestImageStencilDataMethods.cxx,NO_VALID
TestImageStencilIterator.cxx,NO_VALID
TestStencilWithLasso.cxx
--- /dev/null
+/*=========================================================================
+
+ Program: Visualization Toolkit
+ Module: TestImageProbeFilter.cxx
+
+ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
+ All rights reserved.
+ See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
+
+ This software is distributed WITHOUT ANY WARRANTY; without even
+ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the above copyright notice for more information.
+
+=========================================================================*/
+
+#include "vtkImageProbeFilter.h"
+
+#include "vtkNew.h"
+
+#include "vtkActor.h"
+#include "vtkCamera.h"
+#include "vtkDataSetMapper.h"
+#include "vtkImageCast.h"
+#include "vtkImageData.h"
+#include "vtkImageInterpolator.h"
+#include "vtkImageMapToColors.h"
+#include "vtkImageProperty.h"
+#include "vtkImageReader2.h"
+#include "vtkInteractorStyleImage.h"
+#include "vtkLookupTable.h"
+#include "vtkMath.h"
+#include "vtkPlaneSource.h"
+#include "vtkPoints.h"
+#include "vtkRenderWindow.h"
+#include "vtkRenderWindowInteractor.h"
+#include "vtkRenderer.h"
+#include "vtkSphereSource.h"
+#include "vtkTransform.h"
+
+#include <string>
+
+#include "vtkRegressionTestImage.h"
+#include "vtkTestUtilities.h"
+
+int TestImageProbeFilter(int argc, char* argv[])
+{
+ // render window and interactor
+ vtkNew<vtkRenderWindow> renWin;
+ vtkNew<vtkRenderWindowInteractor> iren;
+ iren->SetRenderWindow(renWin);
+ renWin->SetSize(512, 512);
+
+ // image file information (because the file is raw)
+ int extent[6] = { 0, 63, 0, 63, 1, 93 };
+ double origin[3] = { 0.0, 0.0, 0.0 };
+ double spacing[3] = { 3.2, 3.2, 1.5 };
+ char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/headsq/quarter");
+ std::string filename = fname;
+ delete[] fname;
+
+ // read a CT image
+ vtkNew<vtkImageReader2> reader;
+ reader->SetDataByteOrderToLittleEndian();
+ reader->SetDataExtent(extent);
+ reader->SetDataOrigin(origin);
+ reader->SetDataSpacing(spacing);
+ reader->SetFilePrefix(filename.c_str());
+
+ // grayscale lookup table
+ vtkNew<vtkLookupTable> table;
+ table->SetRampToLinear();
+ table->SetRange(0.0, 4095.0);
+ table->SetValueRange(0.0, 1.0);
+ table->SetSaturationRange(0.0, 0.0);
+ table->Build();
+
+ // create RGBA data for rendering
+ vtkNew<vtkImageMapToColors> colors;
+ colors->SetOutputFormatToRGBA();
+ colors->SetInputConnection(reader->GetOutputPort());
+ colors->SetLookupTable(table);
+
+ { // probe RGBA data onto a plane, default probing
+
+ // a plane for probing with
+ vtkNew<vtkPlaneSource> plane;
+ plane->SetOrigin(0.0, 0.0, 69.75);
+ plane->SetPoint1(201.6, 0.0, 69.75);
+ plane->SetPoint2(0.0, 201.6, 69.75);
+ plane->SetXResolution(63);
+ plane->SetYResolution(63);
+
+ // the probe filter
+ vtkNew<vtkImageProbeFilter> probe;
+ probe->SetSourceConnection(colors->GetOutputPort());
+ probe->SetInputConnection(plane->GetOutputPort());
+
+ vtkNew<vtkDataSetMapper> mapper;
+ mapper->SetInputConnection(probe->GetOutputPort());
+
+ vtkNew<vtkActor> actor;
+ actor->SetMapper(mapper);
+
+ vtkNew<vtkRenderer> ren;
+ ren->AddViewProp(actor);
+ ren->ResetCamera();
+ ren->GetActiveCamera()->ParallelProjectionOn();
+ ren->GetActiveCamera()->SetParallelScale(102.4);
+ ren->SetViewport(0.0, 0.5, 0.5, 1.0);
+ renWin->AddRenderer(ren);
+ }
+
+ { // probe RGBA data onto a plane, via cubic interpolation
+
+ // a plane for probing with
+ vtkNew<vtkPlaneSource> plane;
+ plane->SetOrigin(0.0, 0.0, 69.75);
+ plane->SetPoint1(201.6, 0.0, 69.75);
+ plane->SetPoint2(0.0, 201.6, 69.75);
+ plane->SetXResolution(255);
+ plane->SetYResolution(255);
+
+ // an interpolator (cubic interpolation)
+ vtkNew<vtkImageInterpolator> interpolator;
+ interpolator->SetInterpolationModeToCubic();
+
+ // the probe filter
+ vtkNew<vtkImageProbeFilter> probe;
+ probe->SetInterpolator(interpolator);
+ probe->SetSourceConnection(colors->GetOutputPort());
+ probe->SetInputConnection(plane->GetOutputPort());
+
+ vtkNew<vtkDataSetMapper> mapper;
+ mapper->SetInputConnection(probe->GetOutputPort());
+
+ vtkNew<vtkActor> actor;
+ actor->SetMapper(mapper);
+
+ vtkNew<vtkRenderer> ren;
+ ren->AddViewProp(actor);
+ ren->ResetCamera();
+ ren->GetActiveCamera()->ParallelProjectionOn();
+ ren->GetActiveCamera()->SetParallelScale(102.4);
+ ren->SetViewport(0.5, 0.5, 1.0, 1.0);
+ renWin->AddRenderer(ren);
+ }
+
+ { // probe int data onto oblique plane, via cubic interpolation
+
+ // plane information
+ double center[3] = { 100.8, 100.8, 69.75 };
+ double p0[3] = { 0.0, 0.0, 69.75 };
+ double p1[3] = { 201.6, 0.0, 69.75 };
+ double p2[3] = { 0.0, 201.6, 69.75 };
+
+ // a transform for going oblique
+ vtkNew<vtkTransform> transform;
+ transform->PostMultiply();
+ vtkMath::MultiplyScalar(center, -1.0);
+ transform->Translate(center);
+ vtkMath::MultiplyScalar(center, -1.0);
+ transform->RotateWXYZ(-20.0, 0.99388, 0.0, 0.11043);
+ transform->Translate(center);
+ transform->TransformPoint(p0, p0);
+ transform->TransformPoint(p1, p1);
+ transform->TransformPoint(p2, p2);
+
+ // a plane for probing with
+ vtkNew<vtkPlaneSource> plane;
+ plane->SetOrigin(p0);
+ plane->SetPoint1(p1);
+ plane->SetPoint2(p2);
+ plane->SetXResolution(255);
+ plane->SetYResolution(255);
+
+ // an interpolator (cubic interpolation)
+ vtkNew<vtkImageInterpolator> interpolator;
+ interpolator->SetInterpolationModeToCubic();
+
+ // the probe filter
+ vtkNew<vtkImageProbeFilter> probe;
+ probe->SetInterpolator(interpolator);
+ probe->SetSourceConnection(reader->GetOutputPort());
+ probe->SetInputConnection(plane->GetOutputPort());
+
+ vtkNew<vtkDataSetMapper> mapper;
+ mapper->SetInputConnection(probe->GetOutputPort());
+ mapper->SetLookupTable(table);
+ mapper->UseLookupTableScalarRangeOn();
+
+ vtkNew<vtkActor> actor;
+ actor->SetMapper(mapper);
+
+ vtkNew<vtkRenderer> ren;
+ ren->AddViewProp(actor);
+ ren->ResetCamera();
+ ren->GetActiveCamera()->ParallelProjectionOn();
+ ren->GetActiveCamera()->SetParallelScale(102.4);
+ ren->SetViewport(0.0, 0.0, 0.5, 0.5);
+ renWin->AddRenderer(ren);
+ }
+
+ { // probe float data onto sphere, via linear interpolation
+
+ // a sphere for probing with
+ vtkNew<vtkSphereSource> surface;
+ surface->SetCenter(100.8, 100.8, 69.75);
+ surface->SetRadius(60.0);
+ surface->SetPhiResolution(200);
+ surface->SetThetaResolution(200);
+
+ // use floating-point here for coverage
+ vtkNew<vtkImageCast> cast;
+ cast->SetInputConnection(reader->GetOutputPort());
+ cast->SetOutputScalarTypeToFloat();
+
+ // an interpolator (linear interpolation)
+ vtkNew<vtkImageInterpolator> interpolator;
+
+ // the probe filter
+ vtkNew<vtkImageProbeFilter> probe;
+ probe->SetInterpolator(interpolator);
+ probe->SetSourceConnection(cast->GetOutputPort());
+ probe->SetInputConnection(surface->GetOutputPort());
+
+ vtkNew<vtkDataSetMapper> mapper;
+ mapper->SetInputConnection(probe->GetOutputPort());
+ mapper->SetLookupTable(table);
+ mapper->UseLookupTableScalarRangeOn();
+
+ vtkNew<vtkActor> actor;
+ actor->SetMapper(mapper);
+
+ vtkNew<vtkRenderer> ren;
+ ren->AddViewProp(actor);
+ ren->ResetCamera();
+ ren->GetActiveCamera()->ParallelProjectionOn();
+ ren->GetActiveCamera()->SetParallelScale(102.4);
+ ren->SetViewport(0.5, 0.0, 1.0, 0.5);
+ renWin->AddRenderer(ren);
+ }
+
+ renWin->Render();
+
+ int retVal = vtkRegressionTestImage(renWin);
+ if (retVal == vtkRegressionTester::DO_INTERACTOR)
+ {
+ iren->Start();
+ }
+ return !retVal;
+}
--- /dev/null
+cb67b346066f07d9889a844b9caf34b8b79068dfea439cb52b8cadc8bb7a82e8ed6e49ee25ee38a04d3dde89ceb201b99931de7fe9b274ded8117916c90dd3ed
outInfo->Set(vtkDataObject::SPACING(), spacing, 3);
outInfo->Set(vtkDataObject::ORIGIN(), origin, 3);
- vtkInformation* inScalarInfo = vtkDataObject::GetActiveFieldInformation(
- inInfo, vtkDataObject::FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS);
- if (!inScalarInfo)
- {
- vtkErrorMacro("Missing scalar field on input information!");
- return 0;
- }
- vtkDataObject::SetPointDataActiveScalarInfo(outInfo,
- inScalarInfo->Get(vtkDataObject::FIELD_ARRAY_TYPE()),
- inScalarInfo->Get(vtkDataObject::FIELD_NUMBER_OF_COMPONENTS()));
- return 1;
+ return this->RequestInformationBase(inputVector, outputVector);
}
//----------------------------------------------------------------------------
--- /dev/null
+/*=========================================================================
+
+ Program: Visualization Toolkit
+ Module: vtkImageProbeFilter.cxx
+
+ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
+ All rights reserved.
+ See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
+
+ This software is distributed WITHOUT ANY WARRANTY; without even
+ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the above copyright notice for more information.
+
+=========================================================================*/
+#include "vtkImageProbeFilter.h"
+
+#include "vtkImageData.h"
+#include "vtkImageInterpolator.h"
+#include "vtkInformation.h"
+#include "vtkInformationVector.h"
+#include "vtkMath.h"
+#include "vtkObjectFactory.h"
+#include "vtkPointData.h"
+#include "vtkSMPThreadLocal.h"
+#include "vtkSMPTools.h"
+#include "vtkSmartPointer.h"
+#include "vtkStreamingDemandDrivenPipeline.h"
+#include "vtkUnsignedCharArray.h"
+
+#include <algorithm>
+#include <vector>
+
+vtkStandardNewMacro(vtkImageProbeFilter);
+
+vtkCxxSetObjectMacro(vtkImageProbeFilter, Interpolator, vtkAbstractImageInterpolator);
+
+//------------------------------------------------------------------------------
+vtkImageProbeFilter::vtkImageProbeFilter()
+{
+ // Default is no interpolation
+ this->Interpolator = nullptr;
+
+ // Inputs are "Input" and "Source"
+ this->SetNumberOfInputPorts(2);
+
+ // The mask for Input points that intersect the Source image.
+ this->MaskScalars = nullptr;
+
+ // Process active point scalars on "Source" input
+ this->SetInputArrayToProcess(
+ 0, 1, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, vtkDataSetAttributes::SCALARS);
+}
+
+//------------------------------------------------------------------------------
+vtkImageProbeFilter::~vtkImageProbeFilter()
+{
+ if (this->Interpolator)
+ {
+ this->Interpolator->Delete();
+ }
+}
+
+//------------------------------------------------------------------------------
+int vtkImageProbeFilter::FillInputPortInformation(int port, vtkInformation* info)
+{
+ if (port == 1)
+ {
+ info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkImageData");
+ }
+ else
+ {
+ info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataSet");
+ }
+ return 1;
+}
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::SetSourceConnection(vtkAlgorithmOutput* algOutput)
+{
+ this->SetInputConnection(1, algOutput);
+}
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::SetSourceData(vtkDataObject* input)
+{
+ this->SetInputData(1, input);
+}
+
+//------------------------------------------------------------------------------
+vtkDataObject* vtkImageProbeFilter::GetSource()
+{
+ if (this->GetNumberOfInputConnections(1) < 1)
+ {
+ return nullptr;
+ }
+
+ return this->GetExecutive()->GetInputData(1, 0);
+}
+
+//------------------------------------------------------------------------------
+int vtkImageProbeFilter::RequestData(vtkInformation* vtkNotUsed(request),
+ vtkInformationVector** inputVector, vtkInformationVector* outputVector)
+{
+ // get the info objects
+ vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
+ vtkInformation* sourceInfo = inputVector[1]->GetInformationObject(0);
+ vtkInformation* outInfo = outputVector->GetInformationObject(0);
+
+ // get the input and output
+ vtkDataSet* input = vtkDataSet::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
+ vtkImageData* source = vtkImageData::SafeDownCast(sourceInfo->Get(vtkDataObject::DATA_OBJECT()));
+ vtkDataSet* output = vtkDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
+
+ // copy the geometry of the Input to the Output
+ output->CopyStructure(input);
+
+ // probe the Source to generate the Output attributes
+ if (source)
+ {
+ this->Probe(input, source, output);
+ }
+
+ return 1;
+}
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::InitializeForProbing(
+ vtkDataSet* input, vtkImageData* source, vtkDataSet* output)
+{
+ // Get information about the input
+ vtkIdType numPts = input->GetNumberOfPoints();
+ vtkDataArray* inScalars = source->GetPointData()->GetScalars();
+ int scalarType = inScalars->GetDataType();
+ int numComponents = inScalars->GetNumberOfComponents();
+
+ // Prepare the interpolator
+ if (this->Interpolator == nullptr)
+ {
+ vtkImageInterpolator* interp = vtkImageInterpolator::New();
+ interp->SetInterpolationModeToNearest();
+ interp->SetTolerance(0.5);
+ this->Interpolator = interp;
+ }
+ this->Interpolator->Initialize(source);
+ numComponents = this->Interpolator->ComputeNumberOfComponents(numComponents);
+
+ // Create the output scalar array (same type as "Source")
+ vtkDataArray* scalars = vtkDataArray::CreateDataArray(scalarType);
+ scalars->SetNumberOfComponents(numComponents);
+ scalars->SetNumberOfTuples(numPts);
+ scalars->SetName("ImageScalars");
+
+ // Create a scalar array for mask
+ vtkUnsignedCharArray* mask = vtkUnsignedCharArray::New();
+ mask->SetNumberOfComponents(1);
+ mask->SetNumberOfTuples(numPts);
+ mask->SetName("MaskScalars");
+ this->MaskScalars = mask;
+
+ vtkPointData* outPD = output->GetPointData();
+ int idx = outPD->AddArray(scalars);
+ scalars->Delete();
+ outPD->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS);
+ outPD->AddArray(mask);
+ mask->Delete();
+}
+
+//------------------------------------------------------------------------------
+// Thread local storage for the execution of the filter.
+struct vtkImageProbeFilter::ProbePointsThreadLocal
+{
+ ProbePointsThreadLocal()
+ : BaseThread(false)
+ {
+ }
+
+ // Per-thread storage space.
+ std::vector<double> ThreadStore;
+ // BaseThread will be set 'true' for thread that gets first piece.
+ bool BaseThread;
+};
+
+//------------------------------------------------------------------------------
+// This functor is used by vtkSMPTools, it is called by the threads and,
+// in turn, it calls ProbePoints() over a range of points.
+class vtkImageProbeFilter::ProbePointsWorklet
+{
+public:
+ ProbePointsWorklet(
+ vtkImageProbeFilter* probeFilter, vtkDataSet* input, vtkImageData* source, vtkPointData* outPD)
+ : ProbeFilter(probeFilter)
+ , Input(input)
+ , Source(source)
+ , OutPointData(outPD)
+ {
+ }
+
+ void operator()(vtkIdType startId, vtkIdType endId)
+ {
+ if (startId == 0)
+ {
+ this->Thread.Local().BaseThread = true;
+ }
+ this->ProbeFilter->ProbePoints(
+ this->Input, this->Source, this->OutPointData, startId, endId, &this->Thread.Local());
+ }
+
+private:
+ vtkImageProbeFilter* ProbeFilter;
+ vtkDataSet* Input;
+ vtkImageData* Source;
+ vtkPointData* OutPointData;
+ vtkSMPThreadLocal<vtkImageProbeFilter::ProbePointsThreadLocal> Thread;
+};
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::DoProbing(vtkDataSet* input, vtkImageData* source, vtkDataSet* output)
+{
+ vtkDebugMacro(<< "Probing data");
+
+ vtkPointData* outPD = output->GetPointData();
+
+ // Estimate the granularity for multithreading
+ int threads = vtkSMPTools::GetEstimatedNumberOfThreads();
+ vtkIdType numPts = input->GetNumberOfPoints();
+ vtkIdType grain = numPts / threads;
+ vtkIdType minGrain = 100;
+ vtkIdType maxGrain = 1000;
+ grain = vtkMath::ClampValue(grain, minGrain, maxGrain);
+
+ // Multithread the execution
+ ProbePointsWorklet worklet(this, input, source, outPD);
+ vtkSMPTools::For(0, numPts, grain, worklet);
+}
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::Probe(vtkDataSet* input, vtkImageData* source, vtkDataSet* output)
+{
+ // second stage of attribute initialization: initialize from Input
+ this->InitializeForProbing(input, source, output);
+
+ // probe the Source at each Input point
+ this->DoProbing(input, source, output);
+}
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::ProbePoints(vtkDataSet* input, vtkImageData* source, vtkPointData* outPD,
+ vtkIdType startId, vtkIdType endId, ProbePointsThreadLocal* threadLocal)
+{
+ // Get information about the pixels type
+ vtkDataArray* scalars = outPD->GetScalars();
+ double minVal = scalars->GetDataTypeMin();
+ double maxVal = scalars->GetDataTypeMax();
+ int scalarType = scalars->GetDataType();
+ int numComp = scalars->GetNumberOfComponents();
+
+ // Information about the interpolator
+ vtkAbstractImageInterpolator* interpolator = this->Interpolator;
+ int numToClamp = numComp;
+ int numToRound = numComp;
+ if (scalarType == VTK_FLOAT || scalarType == VTK_DOUBLE)
+ {
+ // Only integer data needs clamping or rounding
+ numToClamp = 0;
+ numToRound = 0;
+ }
+ else
+ {
+ vtkImageInterpolator* ii = vtkImageInterpolator::SafeDownCast(interpolator);
+ if (ii && ii->GetInterpolationMode() == VTK_NEAREST_INTERPOLATION)
+ {
+ // Neither clamping nor rounding is used for nearest-neighbor interpolation
+ numToClamp = 0;
+ numToRound = 0;
+ }
+ else if (ii && ii->GetInterpolationMode() == VTK_LINEAR_INTERPOLATION)
+ {
+ // Clamping is only needed for high-order (e.g. cubic, sinc) interpolation.
+ numToClamp = 0;
+ }
+ }
+
+ // We need workspace for pixel computations, use the stack if possible
+ // or use thread-local storage vectors if pixels have >4 components.
+ double storage[8] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
+ double* value = storage;
+ double* zeros = storage + 4;
+ if (numComp > 4)
+ {
+ std::vector<double>& storageVec = threadLocal->ThreadStore;
+ storageVec.resize(numComp * 2, 0);
+ value = storageVec.data();
+ zeros = value + numComp;
+ }
+
+ // The mask array, says which points were within the image.
+ unsigned char* mask = this->MaskScalars->GetPointer(0);
+
+ // Loop over all input points, interpolating source data
+ vtkIdType progressInterval = endId / 20 + 1;
+ for (vtkIdType ptId = startId; ptId < endId && !GetAbortExecute(); ptId++)
+ {
+ if (threadLocal->BaseThread && !(ptId % progressInterval))
+ {
+ // This is not ideal, because if the base thread executes more than one piece,
+ // then the progress will repeat its 0.0 to 1.0 progression for each piece.
+ this->UpdateProgress(static_cast<double>(ptId) / endId);
+ }
+
+ // Get the xyz coordinate of the point in the input dataset
+ double x[3];
+ input->GetPoint(ptId, x);
+
+ // Convert to structured coordinates
+ double ijk[3];
+ source->TransformPhysicalPointToContinuousIndex(x, ijk);
+
+ if (interpolator->CheckBoundsIJK(ijk))
+ {
+ // Do the interpolation
+ interpolator->InterpolateIJK(ijk, value);
+ for (int c = 0; c < numToClamp; c++)
+ {
+ // Clamping is needed to avoid overlow when output is integer
+ value[c] = vtkMath::ClampValue(value[c], minVal, maxVal);
+ }
+ for (int c = 0; c < numToRound; c++)
+ {
+ // This bias results in rounding when SetTuple casts to integer,
+ // e.g. see implementation of vtkMath::Round()
+ value[c] += (value[c] > 0.0 ? 0.5 : -0.5);
+ }
+ scalars->SetTuple(ptId, value);
+ mask[ptId] = 1;
+ }
+ else
+ {
+ // If outside of the image, set to zero
+ scalars->SetTuple(ptId, zeros);
+ mask[ptId] = 0;
+ }
+ }
+}
+
+//------------------------------------------------------------------------------
+int vtkImageProbeFilter::RequestInformation(vtkInformation* vtkNotUsed(request),
+ vtkInformationVector** inputVector, vtkInformationVector* outputVector)
+{
+ // get the info objects
+ vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
+ vtkInformation* sourceInfo = inputVector[1]->GetInformationObject(0);
+ vtkInformation* outInfo = outputVector->GetInformationObject(0);
+
+ // copy extent info from Input to Output
+ outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
+ inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()), 6);
+
+ // copy scalar info from Source to Output
+ int scalarType = vtkImageData::GetScalarType(sourceInfo);
+ int numComponents = vtkImageData::GetNumberOfScalarComponents(sourceInfo);
+ vtkDataObject::SetPointDataActiveScalarInfo(outInfo, scalarType, numComponents);
+
+ return 1;
+}
+
+//------------------------------------------------------------------------------
+int vtkImageProbeFilter::RequestUpdateExtent(vtkInformation* vtkNotUsed(request),
+ vtkInformationVector** inputVector, vtkInformationVector* outputVector)
+{
+ // get the info objects
+ vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
+ vtkInformation* sourceInfo = inputVector[1]->GetInformationObject(0);
+ vtkInformation* outInfo = outputVector->GetInformationObject(0);
+
+ // copy update extent from Output to Input
+ inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1);
+ inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),
+ outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()), 6);
+
+ // set update extent of Source to its whole extent
+ sourceInfo->Remove(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT());
+ if (sourceInfo->Has(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()))
+ {
+ sourceInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),
+ sourceInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()), 6);
+ }
+
+ return 1;
+}
+
+//------------------------------------------------------------------------------
+void vtkImageProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
+{
+ vtkDataObject* source = this->GetSource();
+ vtkAbstractImageInterpolator* interpolator = this->GetInterpolator();
+
+ this->Superclass::PrintSelf(os, indent);
+ os << indent << "Source: " << source << "\n";
+ os << indent << "Interpolator: " << interpolator << "\n";
+}
--- /dev/null
+/*=========================================================================
+
+ Program: Visualization Toolkit
+ Module: vtkImageProbeFilter.h
+
+ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
+ All rights reserved.
+ See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
+
+ This software is distributed WITHOUT ANY WARRANTY; without even
+ the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the above copyright notice for more information.
+
+=========================================================================*/
+/**
+ * @class vtkImageProbeFilter
+ * @brief sample image values at specified point positions
+ *
+ * vtkImageProbeFilter interpolates an image at specified point positions.
+ * This filter has two inputs: the Input and Source. The Input geometric
+ * structure is passed through the filter, and the Output point scalars
+ * are interpolated from the Source image.
+ *
+ * This filter can be used to resample an image onto a set of arbitrarily
+ * placed sample points. For example, if you have a surface data set
+ * (i.e. a vtkPolyData that has been tesselated so that its points are
+ * very closely spaced), you can color the polydata from the image points.
+ *
+ * In general, this filter is similar to vtkProbeFilter except that the
+ * Source data is always an image. The advantages that it provides over
+ * vtkProbeFilter is that it is faster, and it can take advantage of the
+ * advanced interpolation methods offered by vtkAbstractImageInterpolator
+ * subclasses.
+ */
+
+#ifndef vtkImageProbeFilter_h
+#define vtkImageProbeFilter_h
+
+#include "vtkDataSetAlgorithm.h"
+#include "vtkImagingCoreModule.h" // For export macro
+
+class vtkAbstractImageInterpolator;
+class vtkUnsignedCharArray;
+class vtkImageData;
+class vtkPointData;
+
+class VTKIMAGINGCORE_EXPORT vtkImageProbeFilter : public vtkDataSetAlgorithm
+{
+public:
+ static vtkImageProbeFilter* New();
+ vtkTypeMacro(vtkImageProbeFilter, vtkDataSetAlgorithm);
+ void PrintSelf(ostream& os, vtkIndent indent) override;
+
+ //@{
+ /**
+ * Specify the data set that will be probed at the input points.
+ * The Input gives the geometry (the points and cells) for the output,
+ * while the Source is probed (interpolated) to generate the scalars,
+ * vectors, etc. for the output points based on the point locations.
+ */
+ void SetSourceData(vtkDataObject* source);
+ vtkDataObject* GetSource();
+ //@}
+
+ /**
+ * Specify the data set that will be probed at the input points.
+ * The Input gives the geometry (the points and cells) for the output,
+ * while the Source is probed (interpolated) to generate the scalars,
+ * vectors, etc. for the output points based on the point locations.
+ */
+ void SetSourceConnection(vtkAlgorithmOutput* algOutput);
+
+ //@{
+ /**
+ * Set the interpolator to use. If this is not set, then nearest-neighbor
+ * interpolation will be used, with the tolerance of the interpolator set
+ * to 0.5 (half the voxel size).
+ */
+ virtual void SetInterpolator(vtkAbstractImageInterpolator* interpolator);
+ virtual vtkAbstractImageInterpolator* GetInterpolator() { return this->Interpolator; }
+ //@}
+
+protected:
+ vtkImageProbeFilter();
+ ~vtkImageProbeFilter() override;
+
+ int FillInputPortInformation(int port, vtkInformation* info) override;
+
+ int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
+ int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
+ int RequestUpdateExtent(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
+
+ /**
+ * Equivalent to calling InitializeForProbing(); DoProbing().
+ */
+ void Probe(vtkDataSet* input, vtkImageData* source, vtkDataSet* output);
+
+ /**
+ * Initialize the interpolator and the output arrays.
+ */
+ virtual void InitializeForProbing(vtkDataSet* input, vtkImageData* source, vtkDataSet* output);
+
+ /**
+ * Probe appropriate points (InitializeForProbing() must be called first).
+ */
+ void DoProbing(vtkDataSet* input, vtkImageData* source, vtkDataSet* output);
+
+ vtkAbstractImageInterpolator* Interpolator;
+ vtkUnsignedCharArray* MaskScalars;
+
+private:
+ vtkImageProbeFilter(const vtkImageProbeFilter&) = delete;
+ void operator=(const vtkImageProbeFilter&) = delete;
+
+ class ProbePointsWorklet;
+ struct ProbePointsThreadLocal;
+
+ /**
+ * This method is called from the work threads if SMP is used, or called
+ * from the main thread if SMP is not used.
+ */
+ void ProbePoints(vtkDataSet* input, vtkImageData* source, vtkPointData* outPD, vtkIdType startId,
+ vtkIdType endId, ProbePointsThreadLocal* threadLocal);
+};
+
+#endif
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), ext, 6);
outInfo->Set(vtkDataObject::SPACING(), spacing, 3);
- return 1;
+ return this->RequestInformationBase(inputVector, outputVector);
}
void vtkImageResample::PrintSelf(ostream& os, vtkIndent indent)
{
if (this->Interpolator == nullptr)
{
- this->Interpolator = vtkImageInterpolator::New();
+ vtkImageInterpolator* i = vtkImageInterpolator::New();
+ i->SetInterpolationMode(this->InterpolationMode);
+ this->Interpolator = i;
}
return this->Interpolator;
outInfo->Set(vtkDataObject::SPACING(), outSpacing, 3);
outInfo->Set(vtkDataObject::ORIGIN(), outOrigin, 3);
+ return this->RequestInformationBase(inputVector, outputVector);
+}
+
+//------------------------------------------------------------------------------
+int vtkImageReslice::RequestInformationBase(
+ vtkInformationVector** inputVector, vtkInformationVector* outputVector)
+{
+ vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
+ vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkInformation* outStencilInfo = outputVector->GetInformationObject(1);
+
+ int outWholeExt[6];
+ outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), outWholeExt);
+
if (this->GenerateStencilOutput)
{
+ double outSpacing[3], outOrigin[3];
+ outInfo->Get(vtkDataObject::SPACING(), outSpacing);
+ outInfo->Get(vtkDataObject::ORIGIN(), outOrigin);
+
outStencilInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), outWholeExt, 6);
outStencilInfo->Set(vtkDataObject::SPACING(), outSpacing, 3);
outStencilInfo->Set(vtkDataObject::ORIGIN(), outOrigin, 3);
inPtr, outPtr, inputType, inputNumComponents, count, idX, idY, idZ, threadId);
}
+ /**
+ * For derived classes, this should be called at the very end of
+ * RequestInformation() to ensure that various bit and pieces of
+ * state information are correctly set prior to execution.
+ */
+ int RequestInformationBase(vtkInformationVector**, vtkInformationVector*);
+
void GetAutoCroppedOutputBounds(vtkInformation* inInfo, double bounds[6]);
void AllocateOutputData(vtkImageData* output, vtkInformation* outInfo, int* uExtent) override;
vtkImageData* AllocateOutputData(vtkDataObject*, vtkInformation*) override;
}
//----------------------------------------------------------------------------
-std::string vtkPSystemTools::GetCurrentWorkingDirectory(bool collapse)
+std::string vtkPSystemTools::GetCurrentWorkingDirectory(bool /* collapse */)
{
vtkMultiProcessController* controller = vtkMultiProcessController::GetGlobalController();
std::string returnString;
if (controller->GetLocalProcessId() == 0)
{
- returnString = vtksys::SystemTools::GetCurrentWorkingDirectory(collapse);
+ returnString = vtksys::SystemTools::GetCurrentWorkingDirectory();
}
vtkPSystemTools::BroadcastString(returnString, 0);
return returnString;
vtk_fetch_module(vtkDICOM
"Dicom classes and utilities"
GIT_REPOSITORY https://github.com/dgobbi/vtk-dicom
- # vtk-dicom release 8.9.12 plus warning and build fixes
- GIT_TAG d15c9b9100ff1df6caca8cc1073b121cb234396c
+ # vtk-dicom release 0.8.12 plus bug fixes
+ GIT_TAG 324057367c4c1390ed51f0a9bc2000c254d4e811
)
#include "vtkTextProperty.h"
#include "vtkTransform.h"
+#include <algorithm>
+#include <cmath>
+
vtkStandardNewMacro(vtkAxesActor);
vtkCxxSetObjectMacro(vtkAxesActor, UserDefinedTip, vtkPolyData);
// Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
double* vtkAxesActor::GetBounds()
{
- double bounds[6];
- int i;
-
- this->XAxisShaft->GetBounds(this->Bounds);
-
- this->YAxisShaft->GetBounds(bounds);
- for (i = 0; i < 3; ++i)
- {
- this->Bounds[2 * i + 1] = (bounds[2 * i + 1] > this->Bounds[2 * i + 1])
- ? (bounds[2 * i + 1])
- : (this->Bounds[2 * i + 1]);
- }
-
- this->ZAxisShaft->GetBounds(bounds);
- for (i = 0; i < 3; ++i)
- {
- this->Bounds[2 * i + 1] = (bounds[2 * i + 1] > this->Bounds[2 * i + 1])
- ? (bounds[2 * i + 1])
- : (this->Bounds[2 * i + 1]);
- }
+ vtkProp3D* part[6] = { this->XAxisShaft, this->YAxisShaft, this->ZAxisShaft, this->XAxisTip,
+ this->YAxisTip, this->ZAxisTip };
- this->XAxisTip->GetBounds(bounds);
- for (i = 0; i < 3; ++i)
- {
- this->Bounds[2 * i + 1] = (bounds[2 * i + 1] > this->Bounds[2 * i + 1])
- ? (bounds[2 * i + 1])
- : (this->Bounds[2 * i + 1]);
- }
-
- this->YAxisTip->GetBounds(bounds);
- for (i = 0; i < 3; ++i)
- {
- this->Bounds[2 * i + 1] = (bounds[2 * i + 1] > this->Bounds[2 * i + 1])
- ? (bounds[2 * i + 1])
- : (this->Bounds[2 * i + 1]);
- }
-
- this->ZAxisTip->GetBounds(bounds);
- for (i = 0; i < 3; ++i)
+ // We want this actor to rotate / re-center about the origin, so give it
+ // the bounds it would have if the axes were symmetric.
+ double maxbounds[3] = { 0.0, 0.0, 0.0 };
+ double bounds[6];
+ for (int j = 0; j < 6; ++j)
{
- this->Bounds[2 * i + 1] = (bounds[2 * i + 1] > this->Bounds[2 * i + 1])
- ? (bounds[2 * i + 1])
- : (this->Bounds[2 * i + 1]);
+ part[j]->GetBounds(bounds);
+ for (int i = 0; i < 3; ++i)
+ {
+ maxbounds[i] = std::max(maxbounds[i], std::fabs(bounds[2 * i]));
+ maxbounds[i] = std::max(maxbounds[i], std::fabs(bounds[2 * i + 1]));
+ }
}
- // We want this actor to rotate / re-center about the origin, so give it
- // the bounds it would have if the axes were symmetric.
- for (i = 0; i < 3; ++i)
+ for (int i = 0; i < 3; ++i)
{
- this->Bounds[2 * i] = -this->Bounds[2 * i + 1];
+ this->Bounds[2 * i + 1] = maxbounds[i];
+ this->Bounds[2 * i] = -maxbounds[i];
}
return this->Bounds;
vtkRenderingContextOpenGL2
KIT
VTK::OpenGL
+GROUPS
+ Rendering
IMPLEMENTS
VTK::RenderingContext2D
DEPENDS
// modify the data to force a rebuild of OpenGL structs
// after rendering set one cylinder to white
- mapper->SetBlockColor(40, 1.0, 1.0, 1.0);
- mapper->SetBlockOpacity(40, 1.0);
- mapper->SetBlockVisibility(40, 1.0);
+ mapper->SetBlockColor(54, 1.0, 1.0, 1.0);
+ mapper->SetBlockOpacity(54, 1.0);
+ mapper->SetBlockVisibility(54, 1.0);
timer->StartTimer();
win->Render();
for (int i = 0; i <= numFrames; i++)
{
ren->GetActiveCamera()->Elevation(15.0 / numFrames);
- ren->GetActiveCamera()->Azimuth(-130.0 / numFrames);
- ren->GetActiveCamera()->Zoom(pow(1.6, 1.0 / numFrames));
- ren->GetActiveCamera()->Roll(0.0 / numFrames);
+ ren->GetActiveCamera()->Azimuth(-190.0 / numFrames);
+ ren->GetActiveCamera()->Zoom(pow(1.5, 1.0 / numFrames));
+ ren->GetActiveCamera()->Roll(5.0 / numFrames);
win->Render();
}
// modify the data to force a rebuild of OpenGL structs
// after rendering set one cylinder to white
- mapper->SetBlockColor(40, 1.0, 1.0, 1.0);
- mapper->SetBlockOpacity(40, 1.0);
- mapper->SetBlockVisibility(40, 1.0);
+ mapper->SetBlockColor(54, 1.0, 1.0, 1.0);
+ mapper->SetBlockOpacity(54, 1.0);
+ mapper->SetBlockVisibility(54, 1.0);
timer->StartTimer();
win->Render();
for (int i = 0; i <= numFrames; i++)
{
ren->GetActiveCamera()->Elevation(15.0 / numFrames);
- ren->GetActiveCamera()->Azimuth(-130.0 / numFrames);
- ren->GetActiveCamera()->Zoom(pow(1.6, 1.0 / numFrames));
- ren->GetActiveCamera()->Roll(0.0 / numFrames);
+ ren->GetActiveCamera()->Azimuth(-190.0 / numFrames);
+ ren->GetActiveCamera()->Zoom(pow(1.5, 1.0 / numFrames));
+ ren->GetActiveCamera()->Roll(5.0 / numFrames);
win->Render();
}
-c8847c00475ef73475967ded5eed0d0889253d329e47d60439089700b21a666ad1a2312d0bd55b42ff6ecc524ec2a94f07bd6513b823ec60f1c2efec00cdcb4a
+26a26f9b482ece1b1f847d235dce6591a0f74ecfcf808f23bf672b094cbc7e61efb7ce1fa29aae7adab41c2884f70fe1de0769cdf41b640ebeea80de26a3d565
-3c0f5b89defe28e0a194cf67ee42d82e664f93888373e6c0f6329e01765216c547ec03c6137d7b3c75630e0b2981e90b03bafba5216c33f672bfc89175c4300b
+177a7a65d5c9ed9a5258b0e01aefe935bc2f8bbe6b2c614c127ca84ecb6929b7029845a099a41b9047c1efaaf2c09e9d892bcfc108fe827bc19e74dc518cf52f
-ebc6e64968ac8b90f20ac27fd460d95fca692411ffac6c65b0f9ba89958060c75a221d01266a4d2f784e32d555b9e1fbbdfea1c560fefa0ebcc2e7fbc241b962
+59479a0a8eddf76f4ae21118194029dfa8c44dbef81755558fb7f3f73eaa70f062cabcea1d9f0f14cdd6dec958ceb025005ad0baecd28627c6dbb58b4e3929b0
-c953c2d33cbe54b660b8466d7b21ac62aba358c14090b8d24471308835bab37b391dc6dcb1738839c5669fb1d64e2acd249e148e2757050b0cb1da29871d97fd
+5e2ccb83f59d707af4e684ba36706f80f389508b92b3bec04bd5792eaa56968b697951b9eb75d1b6ccf66b21226d3cf200e80dcdf5c9272489e9b14a130dca32
-bde7376a2a94383bfc0a48f4a0679b5e026863a5bcad96f542994eb6c8aa11d56826fb8bd423a30b8c6f7dfb32b3b2b320a32aa51698e81b1a6879fe42aea397
+fb4ca4b6fa5cc5a19742c11ed21cf2b94e22624d456e2379a7dd4c8ef7230510e30c287d215b88adcc4a1a309846c1ad5ff5b602db0197b44549860fb64f8794
-8f8a19e439734e12fd89b0965dc03be71b1f32838660fbd48d98d67d2152d4aa788d5e0a69374d057f87a59e9db12479aede7bd2ae6ea93720c6d24fb5dc75ab
+e045b00ec033132a80fa3200e24eb84dfc63e9a63d2698b5ae916cbe0e19915a581e47a848e8d2718c3c98aa12979c63c246aa356e7bff6e75c3a58044079474
return data;
}
}
- else
- {
- ++current_flat_index;
- }
}
}
//----------------------------------------------------------------------------
// Table is built as a linear ramp between MinimumTableValue and
// MaximumTableValue.
-void vtkWindowLevelLookupTable::Build()
+void vtkWindowLevelLookupTable::ForceBuild()
{
- if (this->Table->GetNumberOfTuples() < 1 ||
- (this->GetMTime() > this->BuildTime && this->InsertTime < this->BuildTime))
- {
- int i, j;
- unsigned char* rgba;
- double start[4], incr[4];
+ double start[4], incr[4];
- for (j = 0; j < 4; j++)
- {
- start[j] = this->MinimumTableValue[j] * 255;
- incr[j] = ((this->MaximumTableValue[j] - this->MinimumTableValue[j]) /
- (this->NumberOfColors - 1) * 255);
- }
+ for (int j = 0; j < 4; j++)
+ {
+ start[j] = this->MinimumTableValue[j] * 255;
+ incr[j] = ((this->MaximumTableValue[j] - this->MinimumTableValue[j]) /
+ (this->NumberOfColors - 1) * 255);
+ }
- if (this->InverseVideo)
+ if (this->InverseVideo)
+ {
+ for (vtkIdType i = 0; i < this->NumberOfColors; i++)
{
- for (i = 0; i < this->NumberOfColors; i++)
+ unsigned char* rgba = this->Table->WritePointer(4 * i, 4);
+ for (int j = 0; j < 4; j++)
{
- rgba = this->Table->WritePointer(4 * i, 4);
- for (j = 0; j < 4; j++)
- {
- rgba[j] =
- static_cast<unsigned char>(start[j] + (this->NumberOfColors - i - 1) * incr[j] + 0.5);
- }
+ rgba[j] =
+ static_cast<unsigned char>(start[j] + (this->NumberOfColors - i - 1) * incr[j] + 0.5);
}
}
- else
+ }
+ else
+ {
+ for (vtkIdType i = 0; i < this->NumberOfColors; i++)
{
- for (i = 0; i < this->NumberOfColors; i++)
+ unsigned char* rgba = this->Table->WritePointer(4 * i, 4);
+ for (int j = 0; j < 4; j++)
{
- rgba = this->Table->WritePointer(4 * i, 4);
- for (j = 0; j < 4; j++)
- {
- rgba[j] = static_cast<unsigned char>(start[j] + i * incr[j] + 0.5);
- }
+ rgba[j] = static_cast<unsigned char>(start[j] + i * incr[j] + 0.5);
}
}
}
+
+ this->BuildSpecialColors();
+
this->BuildTime.Modified();
}
* Generate lookup table as a linear ramp between MinimumTableValue
* and MaximumTableValue.
*/
- void Build() override;
+ void ForceBuild() override;
//@{
/**
}
//----------------------------------------------------------------------------
-FT_CALLBACK_DEF(FT_Error)
-vtkFreeTypeToolsFaceRequester(
+static FT_Error vtkFreeTypeToolsFaceRequester(
FTC_FaceID face_id, FT_Library lib, FT_Pointer request_data, FT_Face* face)
{
#if VTK_FTFC_DEBUG_CD
namespace
{
// The FreeType face requester callback:
-FT_CALLBACK_DEF(FT_Error)
-vtkFontConfigFreeTypeToolsFaceRequester(
+static FT_Error vtkFontConfigFreeTypeToolsFaceRequester(
FTC_FaceID face_id, FT_Library lib, FT_Pointer request_data, FT_Face* face)
{
// Get a pointer to the current vtkFontConfigFreeTypeTools object
# Compile the PNGCompare test, which is used to validate PNG images (read from
# disk, not generated in VTK).
-list(APPEND tests PNGCompare)
+list(APPEND tests PNGCompare.cxx)
vtk_test_cxx_executable(vtkRenderingGL2PSOpenGL2CxxTests tests RENDERING_FACTORY)
blocks[parent]->SetBlock(block, (block % 2) ? nullptr : child.GetPointer());
blocks[parent]->GetMetaData(block)->Set(vtkCompositeDataSet::NAME(), blockName.c_str());
// test not setting it on some
- if (block % 11)
+ if (block % 7)
{
double r, g, b;
- vtkMath::HSVToRGB(0.8 * block / nblocks, 0.2 + 0.8 * ((parent - levelStart) % 8) / 7.0,
+ vtkMath::HSVToRGB(0.8 * block / nblocks, 0.2 + 0.8 * ((parent - levelStart) % 4) / 3.0,
1.0, &r, &g, &b);
mapper->SetBlockColor(parent + numLeaves + 1, r, g, b);
- mapper->SetBlockVisibility(parent + numLeaves, (block % 7) != 0);
+ mapper->SetBlockVisibility(parent + numLeaves, (block % 3) != 0);
vtkMath::HSVToRGB(0.2 + 0.8 * block / nblocks,
- 0.7 + 0.3 * ((parent - levelStart) % 8) / 7.0, 1.0, &r, &g, &b);
+ 0.7 + 0.3 * ((parent - levelStart) % 4) / 3.0, 1.0, &r, &g, &b);
mapper2->SetBlockColor(parent + numLeaves + 1, r, g, b);
- mapper2->SetBlockVisibility(parent + numLeaves, (block % 7) != 0);
+ mapper2->SetBlockVisibility(parent + numLeaves, (block % 3) != 0);
}
++numLeaves;
}
-653fd577fdbbf71e3c08587617a88d95601e57ff5e4654300d0448b59c6cb226e43e4bb5c12380f3805c1c237f3b77b03746d4e6186fbed64f8f4f9c75d86fb1
+5f0ba78fe7d54bc7747e3305639343b12e2d2c789f9ea5c6e90a1cc1fc05568acbd384699e5391f533328f33aba38d4256c0667fc029704b60c5c60b2ba633bd
--- /dev/null
+898a87a22a8d1c009484a6127cdff8f4055542e60ce5836c737bd549d4f97af1a9fa110ae54a20148f054f3fdd37c982fa1111291e0fb598fab9d55f4e64c1c8
-5372aeed03ac6342df4002c4eafe2e4cd4c73d01cde2e70cdbb36a90241970c779785831a398918293225e3ae4d8c3780f848875cfb6cde101f4b9bb6360c037
+9747ee126aa106d60ebfd747828390ba4a7ff0a271cf54d920a1606bc3eb40ef1380c219e5987d8dc4c3fdb77ed86dc80a68442dfc7410aacdee7d966f23a348
IMPLEMENTABLE
KIT
VTK::OpenGL
+GROUPS
+ Rendering
IMPLEMENTS
VTK::RenderingCore
DEPENDS
#import "vtkCocoaRenderWindowInteractor.h"
#import "vtkCommand.h"
#import "vtkNew.h"
+#import "vtkOpenGLState.h"
#import "vtkStringArray.h"
//----------------------------------------------------------------------------
if (_myVTKRenderWindow && _myVTKRenderWindow->GetMapped())
{
+ vtkOpenGLState* state = _myVTKRenderWindow->GetState();
+ state->ResetGLScissorState();
+ vtkOpenGLState::ScopedglScissor ss(state);
+
_myVTKRenderWindow->Render();
}
}
// then check that the drawable is valid
NSOpenGLContext* context = (NSOpenGLContext*)this->GetContextId();
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
bool ok = [context view] != nil;
+#pragma clang diagnostic pop
return win && ok;
}
// SetParentId() was added for) then the Tk superview handles the events.
NSRect glRect = NSMakeRect(x, y, width, height);
NSView* glView = [[NSView alloc] initWithFrame:glRect];
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[glView setWantsBestResolutionOpenGLSurface:wantsBest];
+#pragma clang diagnostic pop
[parent addSubview:glView];
this->SetWindowId(glView);
this->ViewCreated = 1;
// Create a vtkCocoaGLView.
vtkCocoaGLView* glView = [[vtkCocoaGLView alloc] initWithFrame:viewRect];
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[glView setWantsBestResolutionOpenGLSurface:wantsBest];
+#pragma clang diagnostic pop
[window setContentView:glView];
// We have to set the frame's view rect again to work around rounding
// that occurs when setting the window's content view.
if (connectContextToNSView)
{
NSView* view = (NSView*)this->GetWindowId();
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[context setView:view];
+#pragma clang diagnostic pop
}
// the error "invalid drawable" in the console from this call can appear
// This syncs the OpenGL context to the VBL to prevent tearing
GLint one = 1;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[context setValues:&one forParameter:NSOpenGLCPSwapInterval];
+#pragma clang diagnostic pop
}
this->SetPixelFormat((void*)pixelFormat);
if (connectContextToNSView)
{
NSView* view = (NSView*)this->GetWindowId();
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[context setView:view];
+#pragma clang diagnostic pop
}
// the error "invalid drawable" in the console from this call can appear
assert("pre: positive_width" && width > 0);
assert("pre: positive_height" && height > 0);
+#if defined(__APPLE__)
+ // make sure requested multisamples is OK with platform
+ // APPLE Intel systems seem to have buggy multisampled
+ // frambuffer blits etc that cause issues
+ if (this->MultiSamples > 0)
+ {
+ char const* tmp = reinterpret_cast<const char*>(::glGetString(GL_VENDOR));
+ std::string vendor = tmp ? tmp : std::string();
+ if (vendor.find("Intel") != std::string::npos)
+ {
+ this->MultiSamples = 0;
+ }
+ }
+#endif
+
if (this->LastMultiSamples != this->MultiSamples)
{
this->OffScreenFramebuffer->ReleaseGraphicsResources(this);
-dc15c4fbead617b6ac1336568db4a1822f1cad30a94d073e30fb370d0407fc59d2e08c21646f63aaae5c7c185ce827cfeff8e5567eb655e8011156c473cc9b92
+1170a364b05794549c302d78279dbf7681dd4041820ff15a07ef67341e7e5a03767964b867fde2ad76627a565374405b9a7ce118b8497429d8d04aaaf8bdd296
#include "RTWrapper/RTWrapper.h"
+#ifdef __APPLE__
+#include <sys/sysctl.h>
+#include <sys/types.h>
+#endif
+
class vtkOSPRayPassInternals : public vtkRenderPass
{
public:
// ----------------------------------------------------------------------------
void vtkOSPRayPass::RTInit()
{
+ if (!vtkOSPRayPass::IsSupported())
+ {
+ return;
+ }
if (RTDeviceRefCount == 0)
{
rtwInit();
// ----------------------------------------------------------------------------
void vtkOSPRayPass::RTShutdown()
{
+ if (!vtkOSPRayPass::IsSupported())
+ {
+ return;
+ }
--RTDeviceRefCount;
if (RTDeviceRefCount == 0)
{
// ----------------------------------------------------------------------------
void vtkOSPRayPass::Render(const vtkRenderState* s)
{
+ if (!vtkOSPRayPass::IsSupported())
+ {
+ static bool warned = false;
+ if (!warned)
+ {
+ vtkWarningMacro(<< "Ignoring render request because OSPRay is not supported.");
+ warned = true;
+ }
+ return;
+ }
+
vtkRenderer* ren = s->GetRenderer();
if (ren)
{
// ----------------------------------------------------------------------------
void vtkOSPRayPass::RenderInternal(const vtkRenderState* s)
{
+ if (!vtkOSPRayPass::IsSupported())
+ {
+ static bool warned = false;
+ if (!warned)
+ {
+ vtkWarningMacro(<< "Ignoring render request because OSPRay is not supported.");
+ warned = true;
+ }
+ return;
+ }
+
this->NumberOfRenderedProps = 0;
if (this->SceneGraph)
}
}
+// ----------------------------------------------------------------------------
+bool vtkOSPRayPass::IsSupported()
+{
+ static bool detected = false;
+ static bool is_supported = true;
+
+ // Short-circuit to avoid querying on every call.
+ if (detected)
+ {
+ return is_supported;
+ }
+
+ //////////////////////////////////////////////////////////////////////////////
+ // Note that this class is used for OSPRay and OptiX (in addition to any
+ // other RayTracing backends). Currently the only "spoiling" detection is
+ // Apple's Rosetta. Since the only other backend is OptiX today and is not
+ // supported on macOS within VTK anyways, there is no conflict.
+ //////////////////////////////////////////////////////////////////////////////
+
+#ifdef __APPLE__
+ // Detect if we are being translated by Rosetta. OSPRay uses AVX instructions
+ // which are not supported.
+ {
+ int is_translated = 0;
+ size_t size = sizeof(is_translated);
+ if (sysctlbyname("sysctl.proc_translated", &is_translated, &size, nullptr, 0) == -1)
+ {
+ if (errno == ENOENT)
+ {
+ is_translated = 0;
+ }
+ else
+ {
+ // Error occurred. Just continue and let it work if it can or crash if
+ // it doesn't.
+ }
+ }
+ if (is_translated)
+ {
+ is_supported = false;
+ }
+ }
+#endif
+
+ //////////////////////////////////////////////////////////////////////////////
+ // See the comment at the beginning of any conditions.
+ //////////////////////////////////////////////////////////////////////////////
+
+ detected = true;
+ return is_supported;
+}
+
// ----------------------------------------------------------------------------
bool vtkOSPRayPass::IsBackendAvailable(const char* choice)
{
+ if (!vtkOSPRayPass::IsSupported())
+ {
+ return false;
+ }
std::set<RTWBackendType> bends = rtwGetAvailableBackends();
if (!strcmp(choice, "OSPRay raycaster"))
{
static void RTInit();
static void RTShutdown();
+ /**
+ * A run time query to see if OSPRay can possibly work.
+ */
+ static bool IsSupported();
+
/**
* A run time query to see if a particular backend is available.
* Eg. "OSPRay raycaster", "OSPRay pathtracer" or "OptiX pathtracer".
//----------------------------------------------------------------------------
void vtkOSPRayWindowNode::Render(bool prepass)
{
+ if (!vtkOSPRayPass::IsSupported())
+ {
+ static bool warned = false;
+ if (!warned)
+ {
+ vtkWarningMacro(<< "Ignoring render request because OSPRay is not supported.");
+ warned = true;
+ }
+ return;
+ }
+
if (!prepass)
{
// composite all renderers framebuffers together
readonly ownership="HDF Upstream <kwrobot@kitware.com>"
readonly subtree="ThirdParty/$name/vtk$name"
readonly repo="https://gitlab.kitware.com/third-party/hdf5.git"
-readonly tag="for/vtk-20200417-1.10.6"
+readonly tag="for/vtk-20210227-1.10.6"
readonly paths="
CMakeFilters.cmake
CMakeInstallation.cmake
extract_source () {
git_archive
pushd "$extractdir/$name-reduced"
- find -name Makefile.am -delete
- find -name Makefile.in -delete
- find -name "*.lnt" -delete
+ find . -name Makefile.am -delete
+ find . -name Makefile.in -delete
+ find . -name "*.lnt" -delete
rm -v src/.indent.pro
popd
}
doublebyte group;
doublebyte element;
- VRTypes datatype;
+ DICOMTypeValue datatype;
for (int i = 0; i < num_tags; i++)
{
group = dicom_tags[i].group;
element = dicom_tags[i].element;
- datatype = static_cast<VRTypes>(dicom_tags[i].datatype);
+ datatype = static_cast<DICOMTypeValue>(dicom_tags[i].datatype);
Implementation->TypeMap.insert(
dicom_stl::pair<const DICOMMapKey, DICOMTypeValue>(DICOMMapKey(group, element), datatype));
}
/* Decode 4 bytes into a 3 byte string. */
int kwsysBase64_Decode3(const unsigned char* src, unsigned char* dest)
{
- unsigned char d0, d1, d2, d3;
+ unsigned char d0;
+ unsigned char d1;
+ unsigned char d2;
+ unsigned char d3;
d0 = kwsysBase64DecodeChar(src[0]);
d1 = kwsysBase64DecodeChar(src[1]);
set(KWSYS_USE_SystemTools 1)
set(KWSYS_USE_CommandLineArguments 1)
set(KWSYS_USE_Terminal 1)
- set(KWSYS_USE_IOStream 1)
set(KWSYS_USE_FStream 1)
set(KWSYS_USE_String 1)
set(KWSYS_USE_SystemInformation 1)
# capabilities and parent project's request. Enforce 0/1 as only
# possible values for configuration into Configure.hxx.
-# Check existence and uniqueness of long long and __int64.
-KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_LONG_LONG
- "Checking whether C++ compiler has 'long long'" DIRECT)
-KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS___INT64
- "Checking whether C++ compiler has '__int64'" DIRECT)
-if(KWSYS_CXX_HAS___INT64)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_SAME_LONG_AND___INT64
- "Checking whether long and __int64 are the same type" DIRECT)
- if(KWSYS_CXX_HAS_LONG_LONG)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_SAME_LONG_LONG_AND___INT64
- "Checking whether long long and __int64 are the same type" DIRECT)
- endif()
-endif()
-
-# Enable the "long long" type if it is available. It is standard in
-# C99 and C++03 but not in earlier standards.
-if(KWSYS_CXX_HAS_LONG_LONG)
- set(KWSYS_USE_LONG_LONG 1)
-else()
- set(KWSYS_USE_LONG_LONG 0)
-endif()
-
-# Enable the "__int64" type if it is available and unique. It is not
-# standard.
-set(KWSYS_USE___INT64 0)
-if(KWSYS_CXX_HAS___INT64)
- if(NOT KWSYS_CXX_SAME_LONG_AND___INT64)
- if(NOT KWSYS_CXX_SAME_LONG_LONG_AND___INT64)
- set(KWSYS_USE___INT64 1)
- endif()
- endif()
-endif()
-
if(KWSYS_USE_Encoding)
# Look for type size helper macros.
KWSYS_PLATFORM_CXX_TEST(KWSYS_STL_HAS_WSTRING
"Checking whether wstring is available" DIRECT)
endif()
-if(KWSYS_USE_IOStream)
- # Determine whether iostreams support long long.
- if(KWSYS_CXX_HAS_LONG_LONG)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_ISTREAM_LONG_LONG
- "Checking if istream supports long long" DIRECT)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_OSTREAM_LONG_LONG
- "Checking if ostream supports long long" DIRECT)
- else()
- set(KWSYS_IOS_HAS_ISTREAM_LONG_LONG 0)
- set(KWSYS_IOS_HAS_OSTREAM_LONG_LONG 0)
- endif()
- if(KWSYS_CXX_HAS___INT64)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_ISTREAM___INT64
- "Checking if istream supports __int64" DIRECT)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_IOS_HAS_OSTREAM___INT64
- "Checking if ostream supports __int64" DIRECT)
- else()
- set(KWSYS_IOS_HAS_ISTREAM___INT64 0)
- set(KWSYS_IOS_HAS_OSTREAM___INT64 0)
- endif()
-endif()
-
if(KWSYS_NAMESPACE MATCHES "^kwsys$")
set(KWSYS_NAME_IS_KWSYS 1)
else()
set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
COMPILE_DEFINITIONS KWSYS_CXX_HAS_RLIMIT64=1)
endif()
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_ATOL
- "Checking whether CXX compiler has atol" DIRECT)
- if(KWSYS_CXX_HAS_ATOL)
- set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_CXX_HAS_ATOL=1)
- endif()
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_ATOLL
- "Checking whether CXX compiler has atoll" DIRECT)
- if(KWSYS_CXX_HAS_ATOLL)
- set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_CXX_HAS_ATOLL=1)
- endif()
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS__ATOI64
- "Checking whether CXX compiler has _atoi64" DIRECT)
- if(KWSYS_CXX_HAS__ATOI64)
- set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_CXX_HAS__ATOI64=1)
- endif()
if(UNIX)
include(CheckIncludeFileCXX)
# check for simple stack trace
endif()
endif()
endif()
- if(BORLAND)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_BORLAND_ASM
- "Checking whether Borland CXX compiler supports assembler instructions" DIRECT)
- if(KWSYS_CXX_HAS_BORLAND_ASM)
- set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_CXX_HAS_BORLAND_ASM=1)
- KWSYS_PLATFORM_CXX_TEST(KWSYS_CXX_HAS_BORLAND_ASM_CPUID
- "Checking whether Borland CXX compiler supports CPUID assembler instruction" DIRECT)
- if(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
- set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_CXX_HAS_BORLAND_ASM_CPUID=1)
- endif()
- endif()
- endif()
- if(KWSYS_USE___INT64)
- set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_USE___INT64=1)
- endif()
- if(KWSYS_USE_LONG_LONG)
- set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_USE_LONG_LONG=1)
- endif()
- if(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
- set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_IOS_HAS_OSTREAM_LONG_LONG=1)
- endif()
- if(KWSYS_IOS_HAS_OSTREAM___INT64)
- set_property(SOURCE SystemInformation.cxx testSystemInformation.cxx APPEND PROPERTY
- COMPILE_DEFINITIONS KWSYS_IOS_HAS_OSTREAM___INT64=1)
- endif()
if(KWSYS_BUILD_SHARED)
set_property(SOURCE SystemInformation.cxx APPEND PROPERTY
COMPILE_DEFINITIONS KWSYS_BUILD_SHARED=1)
set(KWSYS_H_FILES Configure SharedForward)
set(KWSYS_HXX_FILES Configure String)
-if(NOT CMake_SOURCE_DIR)
- set(KWSYS_HXX_FILES ${KWSYS_HXX_FILES}
- hashtable hash_fun hash_map hash_set
- )
-endif()
-
# Add selected C++ classes.
set(cppclasses
Directory DynamicLoader Encoding Glob RegularExpression SystemTools
- CommandLineArguments IOStream FStream SystemInformation ConsoleBuf
+ CommandLineArguments FStream SystemInformation ConsoleBuf
)
foreach(cpp ${cppclasses})
if(KWSYS_USE_${cpp})
endforeach()
# C++ tests
- if(NOT WATCOM AND NOT CMake_SOURCE_DIR)
- set(KWSYS_CXX_TESTS
- testHashSTL.cxx
- )
- endif()
set(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS}
testConfigure.cxx
testSystemTools.cxx
add_executable(${KWSYS_NAMESPACE}TestProcess testProcess.c)
set_property(TARGET ${KWSYS_NAMESPACE}TestProcess PROPERTY LABELS ${KWSYS_LABELS_EXE})
target_link_libraries(${KWSYS_NAMESPACE}TestProcess ${KWSYS_TARGET_C_LINK})
- if(NOT CYGWIN)
- set(KWSYS_TEST_PROCESS_7 7)
- endif()
+ #set(KWSYS_TEST_PROCESS_7 7) # uncomment to run timing-sensitive test locally
foreach(n 1 2 3 4 5 6 ${KWSYS_TEST_PROCESS_7} 9 10)
add_test(kwsys.testProcess-${n} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestProcess ${n})
set_property(TEST kwsys.testProcess-${n} PROPERTY LABELS ${KWSYS_LABELS_TEST})
set(CTEST_PROJECT_NAME "KWSys")
set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
-set(CTEST_DROP_METHOD "http")
+if (NOT CTEST_DROP_METHOD STREQUAL "https")
+ set(CTEST_DROP_METHOD "http")
+endif ()
set(CTEST_DROP_SITE "open.cdash.org")
set(CTEST_DROP_LOCATION "/submit.php?project=KWSys")
set(CTEST_DROP_SITE_CDASH TRUE)
#include <sstream>
#include <vector>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
#ifdef _MSC_VER
# pragma warning(disable : 4786)
/* Disable some warnings inside kwsys source files. */
#if defined(KWSYS_NAMESPACE)
-# if defined(__BORLANDC__)
-# pragma warn - 8027 /* function not inlined. */
-# endif
# if defined(__INTEL_COMPILER)
# pragma warning(disable : 1572) /* floating-point equality test */
# endif
# pragma warning(disable : 4710) /* function not inlined */
# pragma warning(disable : 4786) /* identifier truncated in debug info */
# endif
-# if defined(__BORLANDC__) && !defined(__cplusplus)
-/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
- unused parameter using "(param)" syntax (i.e. no cast to void). */
-# pragma warn - 8019
-# endif
#endif
/* MSVC 6.0 in release mode will warn about code it produces with its
# include <sys/stat.h>
# include <sys/types.h>
-// Wide function names can vary depending on compiler:
-# ifdef __BORLANDC__
-# define _wfindfirst_func __wfindfirst
-# define _wfindnext_func __wfindnext
-# else
-# define _wfindfirst_func _wfindfirst
-# define _wfindnext_func _wfindnext
-# endif
-
namespace KWSYS_NAMESPACE {
-bool Directory::Load(const std::string& name)
+bool Directory::Load(const std::string& name, std::string* errorMessage)
{
this->Clear();
-# if (defined(_MSC_VER) && _MSC_VER < 1300) || defined(__BORLANDC__)
- // Older Visual C++ and Embarcadero compilers.
- long srchHandle;
-# else // Newer Visual C++
intptr_t srchHandle;
-# endif
char* buf;
size_t n = name.size();
if (name.back() == '/' || name.back() == '\\') {
struct _wfinddata_t data; // data of current file
// Now put them into the file array
- srchHandle = _wfindfirst_func(
- (wchar_t*)Encoding::ToWindowsExtendedPath(buf).c_str(), &data);
+ srchHandle =
+ _wfindfirst((wchar_t*)Encoding::ToWindowsExtendedPath(buf).c_str(), &data);
delete[] buf;
if (srchHandle == -1) {
// Loop through names
do {
this->Internal->Files.push_back(Encoding::ToNarrow(data.name));
- } while (_wfindnext_func(srchHandle, &data) != -1);
+ } while (_wfindnext(srchHandle, &data) != -1);
this->Internal->Path = name;
return _findclose(srchHandle) != -1;
}
-unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
+unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name,
+ std::string* errorMessage)
{
-# if (defined(_MSC_VER) && _MSC_VER < 1300) || defined(__BORLANDC__)
- // Older Visual C++ and Embarcadero compilers.
- long srchHandle;
-# else // Newer Visual C++
intptr_t srchHandle;
-# endif
char* buf;
size_t n = name.size();
if (name.back() == '/') {
struct _wfinddata_t data; // data of current file
// Now put them into the file array
- srchHandle =
- _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+ srchHandle = _wfindfirst((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
delete[] buf;
if (srchHandle == -1) {
unsigned long count = 0;
do {
count++;
- } while (_wfindnext_func(srchHandle, &data) != -1);
+ } while (_wfindnext(srchHandle, &data) != -1);
_findclose(srchHandle);
return count;
}
# include <sys/types.h>
# include <dirent.h>
+# include <errno.h>
+# include <string.h>
// PGI with glibc has trouble with dirent and large file support:
// http://www.pgroup.com/userforum/viewtopic.php?
namespace KWSYS_NAMESPACE {
-bool Directory::Load(const std::string& name)
+bool Directory::Load(const std::string& name, std::string* errorMessage)
{
this->Clear();
+ errno = 0;
DIR* dir = opendir(name.c_str());
if (!dir) {
+ if (errorMessage != nullptr) {
+ *errorMessage = std::string(strerror(errno));
+ }
return false;
}
+ errno = 0;
for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) {
this->Internal->Files.emplace_back(d->d_name);
}
+ if (errno != 0) {
+ if (errorMessage != nullptr) {
+ *errorMessage = std::string(strerror(errno));
+ }
+ return false;
+ }
+
this->Internal->Path = name;
closedir(dir);
return true;
}
-unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name)
+unsigned long Directory::GetNumberOfFilesInDirectory(const std::string& name,
+ std::string* errorMessage)
{
+ errno = 0;
DIR* dir = opendir(name.c_str());
if (!dir) {
+ if (errorMessage != nullptr) {
+ *errorMessage = std::string(strerror(errno));
+ }
return 0;
}
for (kwsys_dirent* d = readdir(dir); d; d = readdir(dir)) {
count++;
}
+ if (errno != 0) {
+ if (errorMessage != nullptr) {
+ *errorMessage = std::string(strerror(errno));
+ }
+ return false;
+ }
+
closedir(dir);
return count;
}
* in that directory. 0 is returned if the directory can not be
* opened, 1 if it is opened.
*/
- bool Load(const std::string&);
+ bool Load(const std::string&, std::string* errorMessage = nullptr);
/**
* Return the number of files in the current directory.
* Return the number of files in the specified directory.
* A higher performance static method.
*/
- static unsigned long GetNumberOfFilesInDirectory(const std::string&);
+ static unsigned long GetNumberOfFilesInDirectory(
+ const std::string&, std::string* errorMessage = nullptr);
/**
* Return the file at the given index, the indexing is 0 based
// should have a tool to help get the symbol with the desired
// calling convention. Currently we assume cdecl.
//
- // Borland:
- // __cdecl = "_func" (default)
- // __fastcall = "@_func"
- // __stdcall = "func"
- //
- // Watcom:
- // __cdecl = "_func"
- // __fastcall = "@_func@X"
- // __stdcall = "_func@X"
- // __watcall = "func_" (default)
- //
// MSVC:
// __cdecl = "func" (default)
// __fastcall = "@_func@X"
// Note that the "@X" part of the name above is the total size (in
// bytes) of the arguments on the stack.
void* result;
-# if defined(__BORLANDC__) || defined(__WATCOMC__)
- // Need to prepend symbols with '_'
- std::string ssym = '_' + sym;
- const char* rsym = ssym.c_str();
-# else
const char* rsym = sym.c_str();
-# endif
result = (void*)GetProcAddress(lib, rsym);
-// Hack to cast pointer-to-data to pointer-to-function.
-# ifdef __WATCOMC__
- return *(DynamicLoader::SymbolPointer*)(&result);
-# else
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
-# endif
}
# define DYNLOAD_ERROR_BUFFER_SIZE 1024
# include "Encoding.hxx.in"
#endif
-#include <stdlib.h>
-#include <string.h>
+#include <cstdlib>
+#include <cstring>
#include <vector>
#ifdef _MSC_VER
FILE* file_;
};
+template <typename CharType, typename Traits = std::char_traits<CharType> >
+class basic_fstream
+ : public std::basic_iostream<CharType, Traits>
+ , public basic_efilebuf<CharType, Traits>
+{
+public:
+ typedef typename basic_efilebuf<CharType, Traits>::internal_buffer_type
+ internal_buffer_type;
+ typedef std::basic_iostream<CharType, Traits> internal_stream_type;
+
+ basic_fstream()
+ : internal_stream_type(new internal_buffer_type())
+ {
+ this->buf_ =
+ static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+ }
+ explicit basic_fstream(char const* file_name,
+ std::ios_base::openmode mode = std::ios_base::in |
+ std::ios_base::out)
+ : internal_stream_type(new internal_buffer_type())
+ {
+ this->buf_ =
+ static_cast<internal_buffer_type*>(internal_stream_type::rdbuf());
+ open(file_name, mode);
+ }
+
+ void open(char const* file_name,
+ std::ios_base::openmode mode = std::ios_base::in |
+ std::ios_base::out)
+ {
+ this->_set_state(this->_open(file_name, mode), this, this);
+ }
+
+ bool is_open() { return this->_is_open(); }
+
+ void close() { this->_set_state(this->_close(), this, this); }
+
+ using basic_efilebuf<CharType, Traits>::_is_open;
+
+ internal_buffer_type* rdbuf() const { return this->buf_; }
+
+ ~basic_fstream() @KWSYS_NAMESPACE@_FStream_NOEXCEPT { close(); }
+};
+
template <typename CharType, typename Traits = std::char_traits<CharType> >
class basic_ifstream
: public std::basic_istream<CharType, Traits>
~basic_ofstream() @KWSYS_NAMESPACE@_FStream_NOEXCEPT { close(); }
};
+typedef basic_fstream<char> fstream;
typedef basic_ifstream<char> ifstream;
typedef basic_ofstream<char> ofstream;
# undef @KWSYS_NAMESPACE@_FStream_NOEXCEPT
#else
+using std::fstream;
using std::ofstream;
using std::ifstream;
#endif
#include <string>
#include <vector>
-#include <ctype.h>
-#include <stdio.h>
-#include <string.h>
+#include <cctype>
+#include <cstdio>
+#include <cstring>
namespace KWSYS_NAMESPACE {
-#if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
+#if defined(_WIN32) || defined(__APPLE__)
// On Windows and Apple, no difference between lower and upper case
# define KWSYS_GLOB_CASE_INDEPENDENT
#endif
const std::string& dir, GlobMessages* messages)
{
kwsys::Directory d;
- if (!d.Load(dir)) {
+ std::string errorMessage;
+ if (!d.Load(dir, &errorMessage)) {
+ if (messages) {
+ if (!errorMessage.empty()) {
+ messages->push_back(Message(Glob::warning,
+ "Error listing directory '" + dir +
+ "'! Reason: '" + errorMessage + "'"));
+ }
+ }
return true;
}
unsigned long cc;
// std::cout << "ProcessDirectory: " << dir << std::endl;
bool last = (start == this->Internals->Expressions.size() - 1);
if (last && this->Recurse) {
- this->RecurseDirectory(start, dir, messages);
+ if (kwsys::SystemTools::FileIsDirectory(dir)) {
+ this->RecurseDirectory(start, dir, messages);
+ }
return;
}
enum MessageType
{
error,
+ warning,
cyclicRecursion
};
bool RecurseListDirs;
private:
- Glob(const Glob&); // Not implemented.
- void operator=(const Glob&); // Not implemented.
+ Glob(const Glob&) = delete;
+ void operator=(const Glob&) = delete;
};
} // namespace @KWSYS_NAMESPACE@
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-#include "kwsysPrivate.h"
-#include KWSYS_HEADER(Configure.hxx)
-
-// Include the streams library.
-#include <iostream>
-#include KWSYS_HEADER(IOStream.hxx)
-
-// Work-around CMake dependency scanning limitation. This must
-// duplicate the above list of headers.
-#if 0
-# include "Configure.hxx.in"
-# include "IOStream.hxx.in"
-#endif
-
-// Implement the rest of this file only if it is needed.
-#if KWSYS_IOS_NEED_OPERATORS_LL
-
-# include <stdio.h> // sscanf, sprintf
-# include <string.h> // memchr
-
-# if defined(_MAX_INT_DIG)
-# define KWSYS_IOS_INT64_MAX_DIG _MAX_INT_DIG
-# else
-# define KWSYS_IOS_INT64_MAX_DIG 32
-# endif
-
-namespace KWSYS_NAMESPACE {
-
-// Scan an input stream for an integer value.
-static int IOStreamScanStream(std::istream& is, char* buffer)
-{
- // Prepare to write to buffer.
- char* out = buffer;
- char* end = buffer + KWSYS_IOS_INT64_MAX_DIG - 1;
-
- // Look for leading sign.
- if (is.peek() == '+') {
- *out++ = '+';
- is.ignore();
- } else if (is.peek() == '-') {
- *out++ = '-';
- is.ignore();
- }
-
- // Determine the base. If not specified in the stream, try to
- // detect it from the input. A leading 0x means hex, and a leading
- // 0 alone means octal.
- int base = 0;
- int flags = is.flags() & std::ios_base::basefield;
- if (flags == std::ios_base::oct) {
- base = 8;
- } else if (flags == std::ios_base::dec) {
- base = 10;
- } else if (flags == std::ios_base::hex) {
- base = 16;
- }
- bool foundDigit = false;
- bool foundNonZero = false;
- if (is.peek() == '0') {
- foundDigit = true;
- is.ignore();
- if ((is.peek() == 'x' || is.peek() == 'X') && (base == 0 || base == 16)) {
- base = 16;
- foundDigit = false;
- is.ignore();
- } else if (base == 0) {
- base = 8;
- }
- }
-
- // Determine the range of digits allowed for this number.
- const char* digits = "0123456789abcdefABCDEF";
- int maxDigitIndex = 10;
- if (base == 8) {
- maxDigitIndex = 8;
- } else if (base == 16) {
- maxDigitIndex = 10 + 6 + 6;
- }
-
- // Scan until an invalid digit is found.
- for (; is.peek() != EOF; is.ignore()) {
- if (memchr(digits, *out = (char)is.peek(), maxDigitIndex) != 0) {
- if ((foundNonZero || *out != '0') && out < end) {
- ++out;
- foundNonZero = true;
- }
- foundDigit = true;
- } else {
- break;
- }
- }
-
- // Correct the buffer contents for degenerate cases.
- if (foundDigit && !foundNonZero) {
- *out++ = '0';
- } else if (!foundDigit) {
- out = buffer;
- }
-
- // Terminate the string in the buffer.
- *out = '\0';
-
- return base;
-}
-
-// Read an integer value from an input stream.
-template <class T>
-std::istream& IOStreamScanTemplate(std::istream& is, T& value, char type)
-{
- int state = std::ios_base::goodbit;
-
- // Skip leading whitespace.
- std::istream::sentry okay(is);
-
- if (okay) {
- try {
- // Copy the string to a buffer and construct the format string.
- char buffer[KWSYS_IOS_INT64_MAX_DIG];
-# if defined(_MSC_VER)
- char format[] = "%I64_";
- const int typeIndex = 4;
-# else
- char format[] = "%ll_";
- const int typeIndex = 3;
-# endif
- switch (IOStreamScanStream(is, buffer)) {
- case 8:
- format[typeIndex] = 'o';
- break;
- case 0: // Default to decimal if not told otherwise.
- case 10:
- format[typeIndex] = type;
- break;
- case 16:
- format[typeIndex] = 'x';
- break;
- };
-
- // Use sscanf to parse the number from the buffer.
- T result;
- int success = (sscanf(buffer, format, &result) == 1) ? 1 : 0;
-
- // Set flags for resulting state.
- if (is.peek() == EOF) {
- state |= std::ios_base::eofbit;
- }
- if (!success) {
- state |= std::ios_base::failbit;
- } else {
- value = result;
- }
- } catch (...) {
- state |= std::ios_base::badbit;
- }
- }
-
- is.setstate(std::ios_base::iostate(state));
- return is;
-}
-
-// Print an integer value to an output stream.
-template <class T>
-std::ostream& IOStreamPrintTemplate(std::ostream& os, T value, char type)
-{
- std::ostream::sentry okay(os);
- if (okay) {
- try {
- // Construct the format string.
- char format[8];
- char* f = format;
- *f++ = '%';
- if (os.flags() & std::ios_base::showpos) {
- *f++ = '+';
- }
- if (os.flags() & std::ios_base::showbase) {
- *f++ = '#';
- }
-# if defined(_MSC_VER)
- *f++ = 'I';
- *f++ = '6';
- *f++ = '4';
-# else
- *f++ = 'l';
- *f++ = 'l';
-# endif
- long bflags = os.flags() & std::ios_base::basefield;
- if (bflags == std::ios_base::oct) {
- *f++ = 'o';
- } else if (bflags != std::ios_base::hex) {
- *f++ = type;
- } else if (os.flags() & std::ios_base::uppercase) {
- *f++ = 'X';
- } else {
- *f++ = 'x';
- }
- *f = '\0';
-
- // Use sprintf to print to a buffer and then write the
- // buffer to the stream.
- char buffer[2 * KWSYS_IOS_INT64_MAX_DIG];
- sprintf(buffer, format, value);
- os << buffer;
- } catch (...) {
- os.clear(os.rdstate() | std::ios_base::badbit);
- }
- }
- return os;
-}
-
-# if !KWSYS_IOS_HAS_ISTREAM_LONG_LONG
-// Implement input stream operator for IOStreamSLL.
-std::istream& IOStreamScan(std::istream& is, IOStreamSLL& value)
-{
- return IOStreamScanTemplate(is, value, 'd');
-}
-
-// Implement input stream operator for IOStreamULL.
-std::istream& IOStreamScan(std::istream& is, IOStreamULL& value)
-{
- return IOStreamScanTemplate(is, value, 'u');
-}
-# endif
-
-# if !KWSYS_IOS_HAS_OSTREAM_LONG_LONG
-// Implement output stream operator for IOStreamSLL.
-std::ostream& IOStreamPrint(std::ostream& os, IOStreamSLL value)
-{
- return IOStreamPrintTemplate(os, value, 'd');
-}
-
-// Implement output stream operator for IOStreamULL.
-std::ostream& IOStreamPrint(std::ostream& os, IOStreamULL value)
-{
- return IOStreamPrintTemplate(os, value, 'u');
-}
-# endif
-
-} // namespace KWSYS_NAMESPACE
-
-#else
-
-namespace KWSYS_NAMESPACE {
-
-// Create one public symbol in this object file to avoid warnings from
-// archivers.
-void IOStreamSymbolToAvoidWarning();
-void IOStreamSymbolToAvoidWarning()
-{
-}
-
-} // namespace KWSYS_NAMESPACE
-
-#endif // KWSYS_IOS_NEED_OPERATORS_LL
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-#ifndef @KWSYS_NAMESPACE@_IOStream_hxx
-#define @KWSYS_NAMESPACE@_IOStream_hxx
-
-#include <iosfwd>
-
-/* Define these macros temporarily to keep the code readable. */
-#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
-#endif
-
-/* Whether istream supports long long. */
-#define @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG \
- @KWSYS_IOS_HAS_ISTREAM_LONG_LONG@
-
-/* Whether ostream supports long long. */
-#define @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG \
- @KWSYS_IOS_HAS_OSTREAM_LONG_LONG@
-
-/* Determine whether we need to define the streaming operators for
- long long or __int64. */
-#if @KWSYS_USE_LONG_LONG@
-# if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG || \
- !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
-# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
-namespace @KWSYS_NAMESPACE@ {
-typedef long long IOStreamSLL;
-typedef unsigned long long IOStreamULL;
-}
-# endif
-#elif defined(_MSC_VER) && _MSC_VER < 1300
-# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
-namespace @KWSYS_NAMESPACE@ {
-typedef __int64 IOStreamSLL;
-typedef unsigned __int64 IOStreamULL;
-}
-#endif
-#if !defined(@KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL)
-# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 0
-#endif
-
-#if @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
-# if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
-
-/* Input stream operator implementation functions. */
-namespace @KWSYS_NAMESPACE@ {
-kwsysEXPORT std::istream& IOStreamScan(std::istream&, IOStreamSLL&);
-kwsysEXPORT std::istream& IOStreamScan(std::istream&, IOStreamULL&);
-}
-
-/* Provide input stream operator for long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_LONG_LONG) && \
- !defined(KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED)
-# define KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_ISTREAM_LONG_LONG_DEFINED
-inline std::istream& operator>>(std::istream& is,
- @KWSYS_NAMESPACE@::IOStreamSLL& value)
-{
- return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
-}
-# endif
-
-/* Provide input stream operator for unsigned long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_UNSIGNED_LONG_LONG) && \
- !defined(KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED)
-# define KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
-inline std::istream& operator>>(std::istream& is,
- @KWSYS_NAMESPACE@::IOStreamULL& value)
-{
- return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
-}
-# endif
-# endif /* !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG */
-
-# if !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
-
-/* Output stream operator implementation functions. */
-namespace @KWSYS_NAMESPACE@ {
-kwsysEXPORT std::ostream& IOStreamPrint(std::ostream&, IOStreamSLL);
-kwsysEXPORT std::ostream& IOStreamPrint(std::ostream&, IOStreamULL);
-}
-
-/* Provide output stream operator for long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_LONG_LONG) && \
- !defined(KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED)
-# define KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_OSTREAM_LONG_LONG_DEFINED
-inline std::ostream& operator<<(std::ostream& os,
- @KWSYS_NAMESPACE@::IOStreamSLL value)
-{
- return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
-}
-# endif
-
-/* Provide output stream operator for unsigned long long. */
-# if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_UNSIGNED_LONG_LONG) && \
- !defined(KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED)
-# define KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
-# define @KWSYS_NAMESPACE@_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
-inline std::ostream& operator<<(std::ostream& os,
- @KWSYS_NAMESPACE@::IOStreamULL value)
-{
- return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
-}
-# endif
-# endif /* !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG */
-#endif /* @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL */
-
-/* Undefine temporary macros. */
-#if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
-# undef kwsysEXPORT
-#endif
-
-/* If building a C++ file in kwsys itself, give the source file
- access to the macros without a configured namespace. */
-#if defined(KWSYS_NAMESPACE)
-# define KWSYS_IOS_HAS_ISTREAM_LONG_LONG \
- @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
-# define KWSYS_IOS_HAS_OSTREAM_LONG_LONG \
- @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
-# define KWSYS_IOS_NEED_OPERATORS_LL @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
-#endif
-
-#endif
static void md5_process(md5_state_t* pms, const md5_byte_t* data /*[64]*/)
{
- md5_word_t a = pms->abcd[0], b = pms->abcd[1], c = pms->abcd[2],
- d = pms->abcd[3];
+ md5_word_t a = pms->abcd[0];
+ md5_word_t b = pms->abcd[1];
+ md5_word_t c = pms->abcd[2];
+ md5_word_t d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
# else
# define xbuf X /* (static only) */
# endif
- for (i = 0; i < 16; ++i, xp += 4)
+ for (i = 0; i < 16; ++i, xp += 4) {
xbuf[i] =
(md5_word_t)(xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24));
+ }
}
#endif
}
size_t offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
- if (nbytes <= 0)
+ if (nbytes <= 0) {
return;
+ }
/* Update the message length. */
pms->count[1] += (md5_word_t)(nbytes >> 29);
pms->count[0] += nbits;
- if (pms->count[0] < nbits)
+ if (pms->count[0] < nbits) {
pms->count[1]++;
+ }
/* Process an initial partial block. */
if (offset) {
size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
- if (offset + copy < 64)
+ if (offset + copy < 64) {
return;
+ }
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
- for (; left >= 64; p += 64, left -= 64)
+ for (; left >= 64; p += 64, left -= 64) {
md5_process(pms, p);
+ }
/* Process a final partial block. */
- if (left)
+ if (left) {
memcpy(pms->buf, p, left);
+ }
}
/* Finish the message and return the digest. */
int i;
/* Save the length before padding. */
- for (i = 0; i < 8; ++i)
+ for (i = 0; i < 8; ++i) {
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+ }
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
- for (i = 0; i < 16; ++i)
+ for (i = 0; i < 16; ++i) {
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+ }
}
#if defined(__clang__) && !defined(__INTEL_COMPILER)
char const* const* c = command;
kwsysProcess_ptrdiff_t n = 0;
kwsysProcess_ptrdiff_t i = 0;
- while (*c++)
- ;
+ while (*c++) {
+ }
n = c - command - 1;
newCommands[cp->NumberOfCommands] =
(char**)malloc((size_t)(n + 1) * sizeof(char*));
{
if (!cp) {
return "Process management structure could not be allocated";
- } else if (cp->State == kwsysProcess_State_Error) {
+ }
+ if (cp->State == kwsysProcess_State_Error) {
return cp->ErrorMessage;
}
return "Success";
{
if (!(cp && cp->ProcessResults && (cp->NumberOfCommands > 0))) {
return "GetExceptionString called with NULL process management structure";
- } else if (cp->State == kwsysProcess_State_Exception) {
+ }
+ if (cp->State == kwsysProcess_State_Exception) {
return cp->ProcessResults[cp->NumberOfCommands - 1].ExitExceptionString;
}
return "No exception";
/* Some platforms specify that the chdir call may be
interrupted. Repeat the call until it finishes. */
- while (((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR))
- ;
+ while (((r = chdir(cp->WorkingDirectory)) < 0) && (errno == EINTR)) {
+ }
if (r < 0) {
kwsysProcessCleanup(cp, 1);
return;
if (cp->RealWorkingDirectory) {
/* Some platforms specify that the chdir call may be
interrupted. Repeat the call until it finishes. */
- while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
- ;
+ while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR)) {
+ }
free(cp->RealWorkingDirectory);
cp->RealWorkingDirectory = 0;
}
if (wd.PipeId) {
/* Data are ready on a pipe. */
return wd.PipeId;
- } else if (wd.Expired) {
+ }
+ if (wd.Expired) {
/* A timeout has expired. */
if (wd.User) {
/* The user timeout has expired. It has no time left. */
return kwsysProcess_Pipe_Timeout;
- } else {
- /* The process timeout has expired. Kill the children now. */
- kwsysProcess_Kill(cp);
- cp->Killed = 0;
- cp->TimeoutExpired = 1;
- return kwsysProcess_Pipe_None;
}
- } else {
- /* No pipes are left open. */
+
+ /* The process timeout has expired. Kill the children now. */
+ kwsysProcess_Kill(cp);
+ cp->Killed = 0;
+ cp->TimeoutExpired = 1;
return kwsysProcess_Pipe_None;
}
+ /* No pipes are left open. */
+ return kwsysProcess_Pipe_None;
}
static int kwsysProcessWaitForPipe(kwsysProcess* cp, char** data, int* length,
read until the operation is not interrupted. */
while (((n = read(cp->PipeReadEnds[i], cp->PipeBuffer,
KWSYSPE_PIPE_BUFFER_SIZE)) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
if (n > 0) {
/* We have data on this pipe. */
if (i == KWSYSPE_PIPE_SIGNAL) {
/* Make sure the set is empty (it should always be empty here
anyway). */
- FD_ZERO(&cp->PipeSet);
+ FD_ZERO(&cp->PipeSet); // NOLINT(readability-isolate-declaration)
/* Setup a timeout if required. */
if (wd->TimeoutTime.tv_sec < 0) {
/* Run select to block until data are available. Repeat call
until it is not interrupted. */
while (((numReady = select(max + 1, &cp->PipeSet, 0, 0, timeout)) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
/* Check result of select. */
if (numReady == 0) {
/* Select's timeout expired. */
wd->Expired = 1;
return 1;
- } else if (numReady < 0) {
+ }
+ if (numReady < 0) {
/* Select returned an error. Leave the error description in the
pipe buffer. */
strncpy(cp->ErrorMessage, strerror(errno), KWSYSPE_PIPE_BUFFER_SIZE);
cp->ProcessResults[prPipe].State = kwsysProcess_StateByIndex_Exited;
cp->ProcessResults[prPipe].ExitException = kwsysProcess_Exception_None;
cp->ProcessResults[prPipe].ExitValue =
+ // NOLINTNEXTLINE(google-readability-casting)
(int)WEXITSTATUS(cp->ProcessResults[prPipe].ExitCode);
} else if (WIFSIGNALED(cp->ProcessResults[prPipe].ExitCode)) {
/* The child received an unhandled signal. */
cp->ProcessResults[prPipe].State = kwsysProcess_State_Exception;
kwsysProcessSetExitExceptionByIndex(
+ // NOLINTNEXTLINE(google-readability-casting)
cp, (int)WTERMSIG(cp->ProcessResults[prPipe].ExitCode), prPipe);
} else {
/* Error getting the child return code. */
/* Reap the child. Keep trying until the call is not
interrupted. */
- while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR))
- ;
+ while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) && (errno == EINTR)) {
+ }
}
}
cp->PipesLeft = 0;
cp->CommandsLeft = 0;
#if KWSYSPE_USE_SELECT
- FD_ZERO(&cp->PipeSet);
+ FD_ZERO(&cp->PipeSet); // NOLINT(readability-isolate-declaration)
#endif
cp->State = kwsysProcess_State_Starting;
cp->Killed = 0;
/* Reap the child. Keep trying until the call is not
interrupted. */
while ((waitpid(cp->ForkPIDs[i], &status, 0) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
}
}
}
/* Restore the working directory. */
if (cp->RealWorkingDirectory) {
- while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR))
- ;
+ while ((chdir(cp->RealWorkingDirectory) < 0) && (errno == EINTR)) {
+ }
}
}
if (pfd && *pfd > 2) {
/* Keep trying to close until it is not interrupted by a
* signal. */
- while ((close(*pfd) < 0) && (errno == EINTR))
- ;
+ while ((close(*pfd) < 0) && (errno == EINTR)) {
+ }
*pfd = -1;
}
}
read until the operation is not interrupted. */
while ((read(cp->PipeReadEnds[i], cp->PipeBuffer,
KWSYSPE_PIPE_BUFFER_SIZE) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
}
#endif
static int kwsysProcessCreate(kwsysProcess* cp, int prIndex,
kwsysProcessCreateInformation* si)
{
- sigset_t mask, old_mask;
+ sigset_t mask;
+ sigset_t old_mask;
int pgidPipe[2];
char tmp;
ssize_t readRes;
/* Make sure the child is in the process group before we proceed. This
avoids race conditions with calls to the kill function that we make for
signalling process groups. */
- while ((readRes = read(pgidPipe[0], &tmp, 1)) > 0)
- ;
+ while ((readRes = read(pgidPipe[0], &tmp, 1)) > 0) {
+ }
if (readRes < 0) {
sigprocmask(SIG_SETMASK, &old_mask, 0);
kwsysProcessCleanupDescriptor(&si->ErrorPipe[0]);
/* Keep trying to read until the operation is not interrupted. */
while (((n = read(si->ErrorPipe[0], cp->ErrorMessage + total,
(size_t)(KWSYSPE_PIPE_BUFFER_SIZE - total))) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
if (n > 0) {
total += n;
}
int i;
/* Temporarily disable signals that access ForkPIDs. We don't want them to
read a reaped PID, and writes to ForkPIDs are not atomic. */
- sigset_t mask, old_mask;
+ sigset_t mask;
+ sigset_t old_mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
int result;
while (((result = waitpid(cp->ForkPIDs[i], &cp->CommandExitCodes[i],
WNOHANG)) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
if (result > 0) {
/* This child has termianted. */
cp->ForkPIDs[i] = 0;
if (timeoutTime->tv_sec < 0) {
/* No timeout time has been requested. */
return 0;
- } else {
- /* Calculate the remaining time. */
- kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
- kwsysProcessTime timeLeft =
- kwsysProcessTimeSubtract(*timeoutTime, currentTime);
- if (timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0) {
- /* Caller has explicitly requested a zero timeout. */
- timeLeft.tv_sec = 0;
- timeLeft.tv_usec = 0;
- }
+ }
+ /* Calculate the remaining time. */
+ kwsysProcessTime currentTime = kwsysProcessTimeGetCurrent();
+ kwsysProcessTime timeLeft =
+ kwsysProcessTimeSubtract(*timeoutTime, currentTime);
+ if (timeLeft.tv_sec < 0 && userTimeout && *userTimeout <= 0) {
+ /* Caller has explicitly requested a zero timeout. */
+ timeLeft.tv_sec = 0;
+ timeLeft.tv_usec = 0;
+ }
- if (timeLeft.tv_sec < 0 ||
- (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired)) {
- /* Timeout has already expired. */
- return 1;
- } else {
- /* There is some time left. */
- timeoutLength->tv_sec = timeLeft.tv_sec;
- timeoutLength->tv_usec = timeLeft.tv_usec;
- return 0;
- }
+ if (timeLeft.tv_sec < 0 ||
+ (timeLeft.tv_sec == 0 && timeLeft.tv_usec == 0 && zeroIsExpired)) {
+ /* Timeout has already expired. */
+ return 1;
}
+ /* There is some time left. */
+ timeoutLength->tv_sec = timeLeft.tv_sec;
+ timeoutLength->tv_usec = timeLeft.tv_usec;
+ return 0;
}
static kwsysProcessTime kwsysProcessTimeGetCurrent(void)
#endif
#ifdef SIGABRT
case SIGABRT:
- KWSYSPE_CASE(Other, "Child aborted");
+ KWSYSPE_CASE(Other, "Subprocess aborted");
break;
#endif
#ifdef SIGKILL
case SIGKILL:
- KWSYSPE_CASE(Other, "Child killed");
+ KWSYSPE_CASE(Other, "Subprocess killed");
break;
#endif
#ifdef SIGTERM
case SIGTERM:
- KWSYSPE_CASE(Other, "Child terminated");
+ KWSYSPE_CASE(Other, "Subprocess terminated");
break;
#endif
#ifdef SIGHUP
if (middle_pid < 0) {
/* Fork failed. Return as if we were not detaching. */
return middle_pid;
- } else if (middle_pid == 0) {
+ }
+ if (middle_pid == 0) {
/* This is the intermediate process. Create the real child. */
pid_t child_pid = fork();
if (child_pid == 0) {
/* This is the real child process. There is nothing to do here. */
return 0;
- } else {
- /* Use the error pipe to report the pid to the real parent. */
- while ((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
- (errno == EINTR))
- ;
-
- /* Exit without cleanup. The parent holds all resources. */
- kwsysProcessExit();
- return 0; /* Never reached, but avoids SunCC warning. */
}
- } else {
- /* This is the original parent process. The intermediate
- process will use the error pipe to report the pid of the
- detached child. */
- pid_t child_pid;
- int status;
- while ((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
- (errno == EINTR))
- ;
+ /* Use the error pipe to report the pid to the real parent. */
+ while ((write(si->ErrorPipe[1], &child_pid, sizeof(child_pid)) < 0) &&
+ (errno == EINTR)) {
+ }
- /* Wait for the intermediate process to exit and clean it up. */
- while ((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR))
- ;
- return child_pid;
+ /* Exit without cleanup. The parent holds all resources. */
+ kwsysProcessExit();
+ return 0; /* Never reached, but avoids SunCC warning. */
}
- } else {
- /* Not creating a detached process. Use normal fork. */
- return fork();
+ /* This is the original parent process. The intermediate
+ process will use the error pipe to report the pid of the
+ detached child. */
+ pid_t child_pid;
+ int status;
+ while ((read(si->ErrorPipe[0], &child_pid, sizeof(child_pid)) < 0) &&
+ (errno == EINTR)) {
+ }
+
+ /* Wait for the intermediate process to exit and clean it up. */
+ while ((waitpid(middle_pid, &status, 0) < 0) && (errno == EINTR)) {
+ }
+ return child_pid;
}
+ /* Not creating a detached process. Use normal fork. */
+ return fork();
}
#endif
/* Make sure the process started and provided a valid header. */
if (ps && fscanf(ps, "%*[^\n]\n") != EOF) {
/* Look for processes whose parent is the process being killed. */
- int pid, ppid;
+ int pid;
+ int ppid;
while (fscanf(ps, KWSYSPE_PS_FORMAT, &pid, &ppid) == 2) {
if (ppid == process_id) {
/* Recursively kill this child and its children. */
sigemptyset(&newSigAction.sa_mask);
while ((sigaction(SIGCHLD, &newSigAction,
&kwsysProcessesOldSigChldAction) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
/* Install our handler for SIGINT / SIGTERM. Repeat call until
it is not interrupted. */
sigaddset(&newSigAction.sa_mask, SIGTERM);
while ((sigaction(SIGINT, &newSigAction,
&kwsysProcessesOldSigIntAction) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
sigemptyset(&newSigAction.sa_mask);
sigaddset(&newSigAction.sa_mask, SIGINT);
while ((sigaction(SIGTERM, &newSigAction,
&kwsysProcessesOldSigIntAction) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
}
}
/* Restore the signal handlers. Repeat call until it is not
interrupted. */
while ((sigaction(SIGCHLD, &kwsysProcessesOldSigChldAction, 0) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
while ((sigaction(SIGINT, &kwsysProcessesOldSigIntAction, 0) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
while ((sigaction(SIGTERM, &kwsysProcessesOldSigTermAction, 0) < 0) &&
- (errno == EINTR))
- ;
+ (errno == EINTR)) {
+ }
/* Free the table of process pointers since it is now empty.
This is safe because the signal handler has been removed. */
#endif
)
{
- int i, j, procStatus, old_errno = errno;
+ int i;
+ int j;
+ int procStatus;
+ int old_errno = errno;
#if KWSYSPE_USE_SIGINFO
(void)info;
(void)ucontext;
memset(&defSigAction, 0, sizeof(defSigAction));
defSigAction.sa_handler = SIG_DFL;
sigemptyset(&defSigAction.sa_mask);
- while ((sigaction(signum, &defSigAction, 0) < 0) && (errno == EINTR))
- ;
+ while ((sigaction(signum, &defSigAction, 0) < 0) && (errno == EINTR)) {
+ }
/* Unmask the signal. */
sigemptyset(&unblockSet);
sigaddset(&unblockSet, signum);
#include <io.h> /* _unlink */
#include <stdio.h> /* sprintf */
#include <string.h> /* strlen, strdup */
-#ifdef __WATCOMC__
-# define _unlink unlink
-#endif
#ifndef _MAX_FNAME
# define _MAX_FNAME 4096
# pragma warning(disable : 4706)
#endif
-#if defined(__BORLANDC__)
-# pragma warn - 8004 /* assigned a value that is never used */
-# pragma warn - 8060 /* Assignment inside if() condition. */
-#endif
-
/* There are pipes for the process pipeline's stdout and stderr. */
#define KWSYSPE_PIPE_COUNT 2
#define KWSYSPE_PIPE_STDOUT 0
kwsysProcessCleanup(cp, GetLastError());
return;
}
- SetCurrentDirectoryW(cp->WorkingDirectory);
+ if (!SetCurrentDirectoryW(cp->WorkingDirectory)) {
+ kwsysProcessCleanup(cp, GetLastError());
+ return;
+ }
}
/* Setup the stdin pipe for the first process. */
# include "RegularExpression.hxx.in"
#endif
-#include <stdio.h>
-#include <string.h>
+#include <cstdio>
+#include <cstring>
namespace KWSYS_NAMESPACE {
this->regmatch.clear();
// Small enough for pointer-storage convention?
- if (comp.regsize >= 32767L) { // Probably could be 65535L.
+ if (comp.regsize >= 65535L) {
// RAISE Error, SYM(RegularExpression), SYM(Expr_Too_Big),
printf("RegularExpression::compile(): Expression too big.\n");
return false;
// Allocate space.
//#ifndef _WIN32
- if (this->program != nullptr)
- delete[] this->program;
+ delete[] this->program;
//#endif
this->program = new char[comp.regsize];
this->progsize = static_cast<int>(comp.regsize);
#include <string>
-/* Disable useless Borland warnings. KWSys tries not to force things
- on its includers, but there is no choice here. */
-#if defined(__BORLANDC__)
-# pragma warn - 8027 /* function not inlined. */
-#endif
-
namespace @KWSYS_NAMESPACE@ {
// Forward declaration
# endif
# endif
-# if defined(__BORLANDC__) && !defined(__cplusplus)
-/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
- unused parameter using "(param)" syntax (i.e. no cast to void). */
-# pragma warn - 8019
-# endif
-
/* Full path to the directory in which this executable is built. Do
not include a trailing slash. */
# if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD)
}
}; // End Class: String
-#if defined(__WATCOMC__)
-inline bool operator<(String const& l, String const& r)
-{
- return (static_cast<std::string const&>(l) <
- static_cast<std::string const&>(r));
-}
-#endif
-
} // namespace @KWSYS_NAMESPACE@
#endif
#else
# include <sys/types.h>
-# include <errno.h> // extern int errno;
+# include <cerrno> // extern int errno;
+# include <csignal>
# include <fcntl.h>
-# include <signal.h>
# include <sys/resource.h> // getrlimit
# include <sys/time.h>
# include <sys/utsname.h> // int uname(struct utsname *buf);
# undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
#endif
-#include <ctype.h> // int isdigit(int c);
+#include <cctype> // int isdigit(int c);
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
#include <memory.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#if defined(KWSYS_USE_LONG_LONG)
-# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)(x))
-# endif
-#elif defined(KWSYS_USE___INT64)
-# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)(x))
-# endif
-#else
-# error "No Long Long"
-#endif
-
-#if defined(KWSYS_CXX_HAS_ATOLL)
-# define atoLongLong atoll
-#else
-# if defined(KWSYS_CXX_HAS__ATOI64)
-# define atoLongLong _atoi64
-# elif defined(KWSYS_CXX_HAS_ATOL)
-# define atoLongLong atol
-# else
-# define atoLongLong atoi
-# endif
-#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64) && \
!defined(__clang__)
# define USE_ASM_INSTRUCTIONS 0
#endif
-#if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(__clang__)
+#if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(__clang__) && \
+ !defined(_M_ARM64)
# include <intrin.h>
# define USE_CPUID_INTRINSICS 1
#else
# define USE_CPUID_INTRINSICS 0
#endif
-#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || \
- defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
+#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS
# define USE_CPUID 1
#else
# define USE_CPUID 0
}
memcpy(result, tmp, sizeof(tmp));
-# elif defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
- unsigned int a, b, c, d;
- __asm {
- mov EAX, select;
- cpuid
- mov a, EAX;
- mov b, EBX;
- mov c, ECX;
- mov d, EDX;
- }
-
- result[0] = a;
- result[1] = b;
- result[2] = c;
- result[3] = d;
# endif
// The cpuid instruction succeeded.
class SystemInformationImplementation
{
public:
- using LongLong = SystemInformation::LongLong;
SystemInformationImplementation();
~SystemInformationImplementation() = default;
size_t GetTotalPhysicalMemory() const;
size_t GetAvailablePhysicalMemory() const;
- LongLong GetProcessId();
+ long long GetProcessId();
// Retrieve memory information in KiB.
- LongLong GetHostMemoryTotal();
- LongLong GetHostMemoryAvailable(const char* hostLimitEnvVarName);
- LongLong GetHostMemoryUsed();
+ long long GetHostMemoryTotal();
+ long long GetHostMemoryAvailable(const char* hostLimitEnvVarName);
+ long long GetHostMemoryUsed();
- LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName,
- const char* procLimitEnvVarName);
- LongLong GetProcMemoryUsed();
+ long long GetProcMemoryAvailable(const char* hostLimitEnvVarName,
+ const char* procLimitEnvVarName);
+ long long GetProcMemoryUsed();
double GetLoadAverage();
Motorola,
HP,
Hygon,
+ Zhaoxin,
+ Apple,
UnknownManufacturer
};
void CPUCountWindows(); // For windows
unsigned char GetAPICId(); // For windows
bool IsSMTSupported() const;
- static LongLong GetCyclesDifference(DELAY_FUNC, unsigned int); // For windows
+ static long long GetCyclesDifference(DELAY_FUNC,
+ unsigned int); // For windows
// For Linux and Cygwin, /proc/cpuinfo formats are slightly different
bool RetreiveInformationFromCpuInfoFile();
const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
{
std::ostringstream oss;
- oss << "Host Total: " << iostreamLongLong(this->GetHostMemoryTotal())
+ oss << "Host Total: " << this->GetHostMemoryTotal()
<< " KiB, Host Available: "
- << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
+ << this->GetHostMemoryAvailable(hostLimitEnvVarName)
<< " KiB, Process Available: "
- << iostreamLongLong(this->GetProcMemoryAvailable(hostLimitEnvVarName,
- procLimitEnvVarName))
+ << this->GetProcMemoryAvailable(hostLimitEnvVarName, procLimitEnvVarName)
<< " KiB";
return oss.str();
}
// host memory info in units of KiB.
-SystemInformation::LongLong SystemInformation::GetHostMemoryTotal()
+long long SystemInformation::GetHostMemoryTotal()
{
return this->Implementation->GetHostMemoryTotal();
}
-SystemInformation::LongLong SystemInformation::GetHostMemoryAvailable(
+long long SystemInformation::GetHostMemoryAvailable(
const char* hostLimitEnvVarName)
{
return this->Implementation->GetHostMemoryAvailable(hostLimitEnvVarName);
}
-SystemInformation::LongLong SystemInformation::GetHostMemoryUsed()
+long long SystemInformation::GetHostMemoryUsed()
{
return this->Implementation->GetHostMemoryUsed();
}
// process memory info in units of KiB.
-SystemInformation::LongLong SystemInformation::GetProcMemoryAvailable(
+long long SystemInformation::GetProcMemoryAvailable(
const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
{
return this->Implementation->GetProcMemoryAvailable(hostLimitEnvVarName,
procLimitEnvVarName);
}
-SystemInformation::LongLong SystemInformation::GetProcMemoryUsed()
+long long SystemInformation::GetProcMemoryUsed()
{
return this->Implementation->GetProcMemoryUsed();
}
return this->Implementation->GetLoadAverage();
}
-SystemInformation::LongLong SystemInformation::GetProcessId()
+long long SystemInformation::GetProcessId()
{
return this->Implementation->GetProcessId();
}
// Hide implementation details in an anonymous namespace.
namespace {
// *****************************************************************************
-#if defined(__linux) || defined(__APPLE__)
+#if defined(__linux) || defined(__APPLE__) || defined(__CYGWIN__)
int LoadLines(FILE* file, std::vector<std::string>& lines)
{
// Load each line in the given file into a the vector.
return nRead;
}
-# if defined(__linux)
+# if defined(__linux) || defined(__CYGWIN__)
// *****************************************************************************
int LoadLines(const char* fileName, std::vector<std::string>& lines)
{
}
#endif
-#if defined(__linux)
+#if defined(__linux) || defined(__CYGWIN__)
// ****************************************************************************
template <typename T>
int GetFieldsFromFile(const char* fileName, const char** fieldNames, T* values)
{
std::string file(path);
if (!this->ReportPath) {
- size_t at = file.rfind("/");
+ size_t at = file.rfind('/');
if (at != std::string::npos) {
file.erase(0, at + 1);
}
case NexGen:
return "NexGen Inc., Advanced Micro Devices";
case IDT:
- return "IDT\\Centaur, Via Inc.";
+ return "IDT\\Centaur, Via Inc., Shanghai Zhaoxin Semiconductor Co., "
+ "Ltd.";
case UMC:
return "United Microelectronics Corp.";
case Rise:
return "Hewlett-Packard";
case Hygon:
return "Chengdu Haiguang IC Design Co., Ltd.";
+ case Zhaoxin:
+ return "Shanghai Zhaoxin Semiconductor Co., Ltd.";
+ case Apple:
+ return "Apple";
case UnknownManufacturer:
default:
return "Unknown Manufacturer";
else if (this->ChipID.Vendor == "NexGenDriven")
this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
else if (this->ChipID.Vendor == "CentaurHauls")
- this->ChipManufacturer = IDT; // IDT/Centaur (now VIA)
+ this->ChipManufacturer = IDT; // original IDT/Centaur/VIA (now Zhaoxin)
+ else if (this->ChipID.Vendor == " Shanghai ")
+ this->ChipManufacturer =
+ Zhaoxin; // Shanghai Zhaoxin Semiconductor Co., Ltd.
else if (this->ChipID.Vendor == "RiseRiseRise")
this->ChipManufacturer = Rise; // Rise
else if (this->ChipID.Vendor == "GenuineTMx86")
this->ChipManufacturer = Motorola; // Motorola Microelectronics
else if (family.compare(0, 7, "PA-RISC") == 0)
this->ChipManufacturer = HP; // Hewlett-Packard
+ else if (this->ChipID.Vendor == "Apple")
+ this->ChipManufacturer = Apple; // Apple
else
this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
}
this->ChipID.ProcessorName = "C3";
break;
default:
- this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+ this->ChipID.ProcessorName =
+ "Unknown IDT\\Centaur\\VIA\\Zhaoxin family";
return false;
}
break;
case 6:
this->ChipID.ProcessorName = "VIA Cyrix III - Samuel";
break;
+ case 0xf:
+ this->ChipID.ProcessorName = "Zhaoxin zxc";
+ break;
+ default:
+ this->ChipID.ProcessorName =
+ "Unknown IDT\\Centaur\\VIA\\Zhaoxin family";
+ return false;
+ }
+ break;
+ case 7:
+ switch (this->ChipID.Model) {
+ case 0x1b:
+ this->ChipID.ProcessorName = "Zhaoxin kx5000";
+ break;
+ case 0x3b:
+ this->ChipID.ProcessorName = "Zhaoxin kx6000";
+ break;
+ default:
+ this->ChipID.ProcessorName =
+ "Unknown IDT\\Centaur\\VIA\\Zhaoxin family";
+ return false;
+ }
+ break;
+ default:
+ this->ChipID.ProcessorName =
+ "Unknown IDT\\Centaur\\VIA\\Zhaoxin family";
+ return false;
+ }
+ break;
+
+ case Zhaoxin:
+ switch (this->ChipID.Family) {
+ case 6:
+ switch (this->ChipID.Model) {
+ case 0x19:
+ this->ChipID.ProcessorName = "Zhaoxin zxc";
+ break;
+ default:
+ this->ChipID.ProcessorName = "Unknown Zhaoxin family";
+ return false;
+ }
+ break;
+ case 7:
+ switch (this->ChipID.Model) {
+ case 0x1b:
+ this->ChipID.ProcessorName = "Zhaoxin kx5000";
+ break;
+ case 0x3b:
+ this->ChipID.ProcessorName = "Zhaoxin kx6000";
+ break;
default:
- this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+ this->ChipID.ProcessorName = "Unknown Zhaoxin family";
return false;
}
break;
default:
- this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
+ this->ChipID.ProcessorName = "Unknown Zhaoxin family";
return false;
}
break;
size_t pos = buffer.find(word, init);
if (pos != std::string::npos) {
this->CurrentPositionInFile = pos;
- pos = buffer.find(":", pos);
- size_t pos2 = buffer.find("\n", pos);
+ pos = buffer.find(':', pos);
+ size_t pos2 = buffer.find('\n', pos);
if (pos != std::string::npos && pos2 != std::string::npos) {
// It may happen that the beginning matches, but this is still not the
// requested key.
pos = buffer.find("processor\t", pos + 1);
}
-#ifdef __linux
+#if defined(__linux) || defined(__CYGWIN__)
// Count sockets.
std::set<int> PhysicalIDs;
std::string idc = this->ExtractValueFromCpuInfoFile(buffer, "physical id");
this->NumberOfPhysicalCPU =
NumberOfCoresPerSocket * (unsigned int)NumberOfSockets;
-#else // __CYGWIN__
- // does not have "physical id" entries, neither "cpu cores"
+#else
+ // For systems which do not have "physical id" entries, neither "cpu cores"
// this has to be fixed for hyper-threading.
std::string cpucount =
this->ExtractValueFromCpuInfoFile(buffer, "cpu count");
/**
Get total system RAM in units of KiB.
*/
-SystemInformation::LongLong
-SystemInformationImplementation::GetHostMemoryTotal()
+long long SystemInformationImplementation::GetHostMemoryTotal()
{
#if defined(_WIN32)
# if defined(_MSC_VER) && _MSC_VER < 1300
GlobalMemoryStatusEx(&statex);
return statex.ullTotalPhys / 1024;
# endif
-#elif defined(__linux)
- SystemInformation::LongLong memTotal = 0;
+#elif defined(__linux) || defined(__CYGWIN__)
+ long long memTotal = 0;
int ierr = GetFieldFromFile("/proc/meminfo", "MemTotal:", memTotal);
if (ierr) {
return -1;
Get total system RAM in units of KiB. This may differ from the
host total if a host-wide resource limit is applied.
*/
-SystemInformation::LongLong
-SystemInformationImplementation::GetHostMemoryAvailable(
+long long SystemInformationImplementation::GetHostMemoryAvailable(
const char* hostLimitEnvVarName)
{
- SystemInformation::LongLong memTotal = this->GetHostMemoryTotal();
+ long long memTotal = this->GetHostMemoryTotal();
// the following mechanism is provided for systems that
// apply resource limits across groups of processes.
if (hostLimitEnvVarName) {
const char* hostLimitEnvVarValue = getenv(hostLimitEnvVarName);
if (hostLimitEnvVarValue) {
- SystemInformation::LongLong hostLimit =
- atoLongLong(hostLimitEnvVarValue);
+ long long hostLimit = std::atoll(hostLimitEnvVarValue);
if (hostLimit > 0) {
memTotal = min(hostLimit, memTotal);
}
Get total system RAM in units of KiB. This may differ from the
host total if a per-process resource limit is applied.
*/
-SystemInformation::LongLong
-SystemInformationImplementation::GetProcMemoryAvailable(
+long long SystemInformationImplementation::GetProcMemoryAvailable(
const char* hostLimitEnvVarName, const char* procLimitEnvVarName)
{
- SystemInformation::LongLong memAvail =
- this->GetHostMemoryAvailable(hostLimitEnvVarName);
+ long long memAvail = this->GetHostMemoryAvailable(hostLimitEnvVarName);
// the following mechanism is provide for systems where rlimits
// are not employed. Units are in KiB.
if (procLimitEnvVarName) {
const char* procLimitEnvVarValue = getenv(procLimitEnvVarName);
if (procLimitEnvVarValue) {
- SystemInformation::LongLong procLimit =
- atoLongLong(procLimitEnvVarValue);
+ long long procLimit = std::atoll(procLimitEnvVarValue);
if (procLimit > 0) {
memAvail = min(procLimit, memAvail);
}
ResourceLimitType rlim;
ierr = GetResourceLimit(RLIMIT_DATA, &rlim);
if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
- memAvail =
- min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ memAvail = min((long long)rlim.rlim_cur / 1024, memAvail);
}
ierr = GetResourceLimit(RLIMIT_AS, &rlim);
if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
- memAvail =
- min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ memAvail = min((long long)rlim.rlim_cur / 1024, memAvail);
}
#elif defined(__APPLE__)
struct rlimit rlim;
int ierr;
ierr = getrlimit(RLIMIT_DATA, &rlim);
if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
- memAvail =
- min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ memAvail = min((long long)rlim.rlim_cur / 1024, memAvail);
}
ierr = getrlimit(RLIMIT_RSS, &rlim);
if ((ierr == 0) && (rlim.rlim_cur != RLIM_INFINITY)) {
- memAvail =
- min((SystemInformation::LongLong)rlim.rlim_cur / 1024, memAvail);
+ memAvail = min((long long)rlim.rlim_cur / 1024, memAvail);
}
#endif
/**
Get RAM used by all processes in the host, in units of KiB.
*/
-SystemInformation::LongLong
-SystemInformationImplementation::GetHostMemoryUsed()
+long long SystemInformationImplementation::GetHostMemoryUsed()
{
#if defined(_WIN32)
# if defined(_MSC_VER) && _MSC_VER < 1300
GlobalMemoryStatusEx(&statex);
return (statex.ullTotalPhys - statex.ullAvailPhys) / 1024;
# endif
+#elif defined(__CYGWIN__)
+ const char* names[3] = { "MemTotal:", "MemFree:", nullptr };
+ long long values[2] = { 0 };
+ int ierr = GetFieldsFromFile("/proc/meminfo", names, values);
+ if (ierr) {
+ return ierr;
+ }
+ long long& memTotal = values[0];
+ long long& memFree = values[1];
+ return memTotal - memFree;
#elif defined(__linux)
// First try to use MemAvailable, but it only works on newer kernels
const char* names2[3] = { "MemTotal:", "MemAvailable:", nullptr };
- SystemInformation::LongLong values2[2] = { SystemInformation::LongLong(0) };
+ long long values2[2] = { 0 };
int ierr = GetFieldsFromFile("/proc/meminfo", names2, values2);
if (ierr) {
const char* names4[5] = { "MemTotal:", "MemFree:", "Buffers:", "Cached:",
nullptr };
- SystemInformation::LongLong values4[4] = { SystemInformation::LongLong(
- 0) };
+ long long values4[4] = { 0 };
ierr = GetFieldsFromFile("/proc/meminfo", names4, values4);
if (ierr) {
return ierr;
}
- SystemInformation::LongLong& memTotal = values4[0];
- SystemInformation::LongLong& memFree = values4[1];
- SystemInformation::LongLong& memBuffers = values4[2];
- SystemInformation::LongLong& memCached = values4[3];
+ long long& memTotal = values4[0];
+ long long& memFree = values4[1];
+ long long& memBuffers = values4[2];
+ long long& memCached = values4[3];
return memTotal - memFree - memBuffers - memCached;
}
- SystemInformation::LongLong& memTotal = values2[0];
- SystemInformation::LongLong& memAvail = values2[1];
+ long long& memTotal = values2[0];
+ long long& memAvail = values2[1];
return memTotal - memAvail;
#elif defined(__APPLE__)
- SystemInformation::LongLong psz = getpagesize();
+ long long psz = getpagesize();
if (psz < 1) {
return -1;
}
const char* names[3] = { "Pages wired down:", "Pages active:", nullptr };
- SystemInformation::LongLong values[2] = { SystemInformation::LongLong(0) };
+ long long values[2] = { 0 };
int ierr = GetFieldsFromCommand("vm_stat", names, values);
if (ierr) {
return -1;
}
- SystemInformation::LongLong& vmWired = values[0];
- SystemInformation::LongLong& vmActive = values[1];
+ long long& vmWired = values[0];
+ long long& vmActive = values[1];
return ((vmActive + vmWired) * psz) / 1024;
#else
return 0;
Get system RAM used by the process associated with the given
process id in units of KiB.
*/
-SystemInformation::LongLong
-SystemInformationImplementation::GetProcMemoryUsed()
+long long SystemInformationImplementation::GetProcMemoryUsed()
{
#if defined(_WIN32) && defined(KWSYS_SYS_HAS_PSAPI)
long pid = GetCurrentProcessId();
return -2;
}
return pmc.WorkingSetSize / 1024;
-#elif defined(__linux)
- SystemInformation::LongLong memUsed = 0;
+#elif defined(__linux) || defined(__CYGWIN__)
+ long long memUsed = 0;
int ierr = GetFieldFromFile("/proc/self/status", "VmRSS:", memUsed);
if (ierr) {
return -1;
}
return memUsed;
#elif defined(__APPLE__)
- SystemInformation::LongLong memUsed = 0;
+ long long memUsed = 0;
pid_t pid = getpid();
std::ostringstream oss;
oss << "ps -o rss= -p " << pid;
/**
Get the process id of the running process.
*/
-SystemInformation::LongLong SystemInformationImplementation::GetProcessId()
+long long SystemInformationImplementation::GetProcessId()
{
#if defined(_WIN32)
return GetCurrentProcessId();
#elif defined(__linux) || defined(__APPLE__) || defined(__OpenBSD__) || \
- defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
+ defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || \
+ defined(__CYGWIN__)
return getpid();
#else
return -1;
int wholePath)
{
std::ostringstream oss;
- std::string programStack = "";
+ std::string programStack;
#ifdef KWSYS_SYSTEMINFORMATION_HAS_DBGHELP
(void)wholePath;
}
/** Get Cycle differences */
-SystemInformation::LongLong
-SystemInformationImplementation::GetCyclesDifference(DELAY_FUNC DelayFunction,
- unsigned int uiParameter)
+long long SystemInformationImplementation::GetCyclesDifference(
+ DELAY_FUNC DelayFunction, unsigned int uiParameter)
{
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
unsigned __int64 stamp1, stamp2;
+# ifdef _M_ARM64
+ stamp1 = _ReadStatusReg(ARM64_PMCCNTR_EL0);
+ DelayFunction(uiParameter);
+ stamp2 = _ReadStatusReg(ARM64_PMCCNTR_EL0);
+# else
stamp1 = __rdtsc();
DelayFunction(uiParameter);
stamp2 = __rdtsc();
+# endif
return stamp2 - stamp1;
#elif USE_ASM_INSTRUCTIONS
DWORD Length = 0;
DWORD rc = pGetLogicalProcessorInformation(nullptr, &Length);
assert(FALSE == rc);
- (void)rc; // Silence unused variable warning in Borland C++ 5.81
+ (void)rc; // Silence unused variable warning
assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);
ProcInfo.resize(Length / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
rc = pGetLogicalProcessorInformation(&ProcInfo[0], &Length);
assert(rc != FALSE);
- (void)rc; // Silence unused variable warning in Borland C++ 5.81
+ (void)rc; // Silence unused variable warning
}
typedef std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION>::iterator
return this->NumberOfPhysicalCPU;
}
-/** For Mac use sysctlbyname calls to find system info */
+#if defined(__APPLE__)
+static int kw_sysctlbyname_int32(const char* name, int32_t* value)
+{
+ size_t len = sizeof(int32_t);
+ int err = sysctlbyname(name, value, &len, nullptr, 0);
+ if (err == 0) {
+ assert(len == sizeof(int32_t));
+ }
+ return err;
+}
+
+static int kw_sysctlbyname_int64(const char* name, int64_t* value)
+{
+ size_t len = sizeof(int64_t);
+ int err = sysctlbyname(name, value, &len, nullptr, 0);
+ if (err == 0) {
+ assert(len == sizeof(int64_t));
+ }
+ return err;
+}
+#endif
+
+/** For Apple use sysctlbyname calls to find system info */
bool SystemInformationImplementation::ParseSysCtl()
{
#if defined(__APPLE__)
- char retBuf[128];
+ char tempBuff[128];
+ int32_t tempInt32 = 0;
+ int64_t tempInt64 = 0;
int err = 0;
- uint64_t value = 0;
- size_t len = sizeof(value);
- sysctlbyname("hw.memsize", &value, &len, nullptr, 0);
- this->TotalPhysicalMemory = static_cast<size_t>(value / 1048576);
+ size_t len;
+
+ this->TotalPhysicalMemory = 0;
+ err = kw_sysctlbyname_int64("hw.memsize", &tempInt64);
+ if (err == 0) {
+ this->TotalPhysicalMemory = static_cast<size_t>(tempInt64 / 1024 / 1024);
+ }
- // Parse values for Mac
this->AvailablePhysicalMemory = 0;
vm_statistics_data_t vmstat;
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat,
&count) == KERN_SUCCESS) {
- len = sizeof(value);
- err = sysctlbyname("hw.pagesize", &value, &len, nullptr, 0);
- int64_t available_memory =
- (vmstat.free_count + vmstat.inactive_count) * value;
- this->AvailablePhysicalMemory =
- static_cast<size_t>(available_memory / 1048576);
+ err = kw_sysctlbyname_int64("hw.pagesize", &tempInt64);
+ if (err == 0) {
+ int64_t available_memory =
+ (vmstat.free_count + vmstat.inactive_count) * tempInt64;
+ this->AvailablePhysicalMemory =
+ static_cast<size_t>(available_memory / 1024 / 1024);
+ }
}
-# ifdef VM_SWAPUSAGE
// Virtual memory.
+ this->AvailableVirtualMemory = 0;
+ this->TotalVirtualMemory = 0;
+# ifdef VM_SWAPUSAGE
int mib[2] = { CTL_VM, VM_SWAPUSAGE };
unsigned int miblen =
static_cast<unsigned int>(sizeof(mib) / sizeof(mib[0]));
err = sysctl(mib, miblen, &swap, &len, nullptr, 0);
if (err == 0) {
this->AvailableVirtualMemory =
- static_cast<size_t>(swap.xsu_avail / 1048576);
- this->TotalVirtualMemory = static_cast<size_t>(swap.xsu_total / 1048576);
+ static_cast<size_t>(swap.xsu_avail / 1024 / 1024);
+ this->TotalVirtualMemory =
+ static_cast<size_t>(swap.xsu_total / 1024 / 1024);
}
-# else
- this->AvailableVirtualMemory = 0;
- this->TotalVirtualMemory = 0;
# endif
// CPU Info
- len = sizeof(this->NumberOfPhysicalCPU);
- sysctlbyname("hw.physicalcpu", &this->NumberOfPhysicalCPU, &len, nullptr, 0);
- len = sizeof(this->NumberOfLogicalCPU);
- sysctlbyname("hw.logicalcpu", &this->NumberOfLogicalCPU, &len, nullptr, 0);
-
- int cores_per_package = 0;
- len = sizeof(cores_per_package);
- err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &len,
- nullptr, 0);
- // That name was not found, default to 1
- this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
- err != 0 ? 1 : static_cast<unsigned char>(cores_per_package);
+ this->NumberOfPhysicalCPU = 1;
+ err = kw_sysctlbyname_int32("hw.physicalcpu", &tempInt32);
+ if (err == 0) {
+ this->NumberOfPhysicalCPU = tempInt32;
+ }
- len = sizeof(value);
- sysctlbyname("hw.cpufrequency", &value, &len, nullptr, 0);
- this->CPUSpeedInMHz = static_cast<float>(value) / 1000000;
+ this->NumberOfLogicalCPU = 1;
+ err = kw_sysctlbyname_int32("hw.logicalcpu", &tempInt32);
+ if (err == 0) {
+ this->NumberOfLogicalCPU = tempInt32;
+ }
+
+ this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = 1;
+ err = kw_sysctlbyname_int32("machdep.cpu.cores_per_package", &tempInt32);
+ if (err == 0) {
+ this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = tempInt32;
+ }
+
+ this->CPUSpeedInMHz = 0;
+ err = kw_sysctlbyname_int64("hw.cpufrequency", &tempInt64);
+ if (err == 0) {
+ this->CPUSpeedInMHz = static_cast<float>(tempInt64) / 1000000.0f;
+ }
// Chip family
- len = sizeof(this->ChipID.Family);
- // Seems only the intel chips will have this name so if this fails it is
- // probably a PPC machine
- err =
- sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, nullptr, 0);
+ // Seems only the Intel chips will have this name so if this fails it is
+ // a PowerPC or ARM, or something unknown
+ this->ChipID.Vendor = "";
+ this->ChipID.Family = 0;
+ this->ChipID.Model = 0;
+ this->ChipID.Revision = 0;
+ err = kw_sysctlbyname_int32("machdep.cpu.family", &tempInt32);
if (err != 0) // Go back to names we know but are less descriptive
{
- this->ChipID.Family = 0;
- ::memset(retBuf, 0, 128);
- len = 32;
- err = sysctlbyname("hw.machine", &retBuf, &len, nullptr, 0);
- std::string machineBuf(retBuf);
- if (machineBuf.find_first_of("Power") != std::string::npos) {
- this->ChipID.Vendor = "IBM";
- len = sizeof(this->ChipID.Family);
- err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, nullptr, 0);
- len = sizeof(this->ChipID.Model);
- err =
- sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, nullptr, 0);
- this->FindManufacturer();
+ ::memset(tempBuff, 0, sizeof(tempBuff));
+ len = sizeof(tempBuff) - 1; // leave a byte for null termination
+ err = sysctlbyname("hw.machine", &tempBuff, &len, nullptr, 0);
+ if (err == 0) {
+ std::string machineBuf(tempBuff);
+ if (machineBuf.find_first_of("Power") != std::string::npos) {
+ this->ChipID.Vendor = "IBM";
+
+ err = kw_sysctlbyname_int32("hw.cputype", &tempInt32);
+ if (err == 0) {
+ this->ChipID.Family = tempInt32;
+ }
+
+ err = kw_sysctlbyname_int32("hw.cpusubtype", &tempInt32);
+ if (err == 0) {
+ this->ChipID.Model = tempInt32;
+ }
+
+ this->FindManufacturer();
+ } else if (machineBuf.find_first_of("arm64") != std::string::npos) {
+ this->ChipID.Vendor = "Apple";
+
+ this->FindManufacturer();
+ }
+ }
+ } else {
+ // Should be an Intel Chip.
+ err = kw_sysctlbyname_int32("machdep.cpu.family", &tempInt32);
+ if (err == 0) {
+ this->ChipID.Family = tempInt32;
}
- } else // Should be an Intel Chip.
- {
- len = sizeof(this->ChipID.Family);
- err = sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len,
- nullptr, 0);
- ::memset(retBuf, 0, 128);
- len = 128;
- err = sysctlbyname("machdep.cpu.vendor", retBuf, &len, nullptr, 0);
// Chip Vendor
- this->ChipID.Vendor = retBuf;
+ ::memset(tempBuff, 0, sizeof(tempBuff));
+ len = sizeof(tempBuff) - 1; // leave a byte for null termination
+ err = sysctlbyname("machdep.cpu.vendor", tempBuff, &len, nullptr, 0);
+ if (err == 0) {
+ this->ChipID.Vendor = tempBuff;
+ }
this->FindManufacturer();
// Chip Model
- len = sizeof(value);
- err = sysctlbyname("machdep.cpu.model", &value, &len, nullptr, 0);
- this->ChipID.Model = static_cast<int>(value);
+ err = kw_sysctlbyname_int32("machdep.cpu.model", &tempInt32);
+ if (err == 0) {
+ this->ChipID.Model = tempInt32;
+ }
// Chip Stepping
- len = sizeof(value);
- value = 0;
- err = sysctlbyname("machdep.cpu.stepping", &value, &len, nullptr, 0);
- if (!err) {
- this->ChipID.Revision = static_cast<int>(value);
+ err = kw_sysctlbyname_int32("machdep.cpu.stepping", &tempInt32);
+ if (err == 0) {
+ this->ChipID.Revision = tempInt32;
}
// feature string
len = allocSize - 2; // keep space for leading and trailing space
err = sysctlbyname("machdep.cpu.features", buf + 1, &len, nullptr, 0);
}
- if (!err && buf && len) {
+ if (err == 0 && buf && len) {
// now we can match every flags as space + flag + space
buf[len + 1] = ' ';
std::string cpuflags(buf, len + 2);
- if ((cpuflags.find(" FPU ") != std::string::npos)) {
+ if (cpuflags.find(" FPU ") != std::string::npos) {
this->Features.HasFPU = true;
}
- if ((cpuflags.find(" TSC ") != std::string::npos)) {
+ if (cpuflags.find(" TSC ") != std::string::npos) {
this->Features.HasTSC = true;
}
- if ((cpuflags.find(" MMX ") != std::string::npos)) {
+ if (cpuflags.find(" MMX ") != std::string::npos) {
this->Features.HasMMX = true;
}
- if ((cpuflags.find(" SSE ") != std::string::npos)) {
+ if (cpuflags.find(" SSE ") != std::string::npos) {
this->Features.HasSSE = true;
}
- if ((cpuflags.find(" SSE2 ") != std::string::npos)) {
+ if (cpuflags.find(" SSE2 ") != std::string::npos) {
this->Features.HasSSE2 = true;
}
- if ((cpuflags.find(" APIC ") != std::string::npos)) {
+ if (cpuflags.find(" APIC ") != std::string::npos) {
this->Features.HasAPIC = true;
}
- if ((cpuflags.find(" CMOV ") != std::string::npos)) {
+ if (cpuflags.find(" CMOV ") != std::string::npos) {
this->Features.HasCMOV = true;
}
- if ((cpuflags.find(" MTRR ") != std::string::npos)) {
+ if (cpuflags.find(" MTRR ") != std::string::npos) {
this->Features.HasMTRR = true;
}
- if ((cpuflags.find(" ACPI ") != std::string::npos)) {
+ if (cpuflags.find(" ACPI ") != std::string::npos) {
this->Features.HasACPI = true;
}
}
}
// brand string
- ::memset(retBuf, 0, sizeof(retBuf));
- len = sizeof(retBuf);
- err = sysctlbyname("machdep.cpu.brand_string", retBuf, &len, nullptr, 0);
- if (!err) {
- this->ChipID.ProcessorName = retBuf;
- this->ChipID.ModelName = retBuf;
+ this->ChipID.ProcessorName = "";
+ this->ChipID.ModelName = "";
+ ::memset(tempBuff, 0, sizeof(tempBuff));
+ len = sizeof(tempBuff) - 1; // leave a byte for null termination
+ err = sysctlbyname("machdep.cpu.brand_string", tempBuff, &len, nullptr, 0);
+ if (err == 0) {
+ this->ChipID.ProcessorName = tempBuff;
+ this->ChipID.ModelName = tempBuff;
}
- // Cache size
- len = sizeof(value);
- err = sysctlbyname("hw.l1icachesize", &value, &len, nullptr, 0);
- this->Features.L1CacheSize = static_cast<int>(value);
- len = sizeof(value);
- err = sysctlbyname("hw.l2cachesize", &value, &len, nullptr, 0);
- this->Features.L2CacheSize = static_cast<int>(value);
+ // L1 Cache size
+ this->Features.L1CacheSize = 0;
+ err = kw_sysctlbyname_int64("hw.l1icachesize", &tempInt64);
+ if (err == 0) {
+ this->Features.L1CacheSize = static_cast<int>(tempInt64);
+ }
+
+ // L2 Cache size
+ this->Features.L2CacheSize = 0;
+ err = kw_sysctlbyname_int64("hw.l2cachesize", &tempInt64);
+ if (err == 0) {
+ this->Features.L2CacheSize = static_cast<int>(tempInt64);
+ }
return true;
#else
size_t pos = this->SysCtlBuffer.find(word);
if (pos != std::string::npos) {
pos = this->SysCtlBuffer.find(": ", pos);
- size_t pos2 = this->SysCtlBuffer.find("\n", pos);
+ size_t pos2 = this->SysCtlBuffer.find('\n', pos);
if (pos != std::string::npos && pos2 != std::string::npos) {
return this->SysCtlBuffer.substr(pos + 2, pos2 - pos - 2);
}
{
// remove \r
std::string::size_type pos = 0;
- while ((pos = output.find("\r", pos)) != std::string::npos) {
+ while ((pos = output.find('\r', pos)) != std::string::npos) {
output.erase(pos);
}
// remove \n
pos = 0;
- while ((pos = output.find("\n", pos)) != std::string::npos) {
+ while ((pos = output.find('\n', pos)) != std::string::npos) {
output.erase(pos);
}
}
class @KWSYS_NAMESPACE@_EXPORT SystemInformation
{
-#if @KWSYS_USE_LONG_LONG@
- typedef long long LongLong;
-#elif @KWSYS_USE___INT64@
- typedef __int64 LongLong;
-#else
-# error "No Long Long"
-#endif
friend class SystemInformationImplementation;
SystemInformationImplementation* Implementation;
bool DoesCPUSupportCPUID();
// Retrieve id of the current running process
- LongLong GetProcessId();
+ long long GetProcessId();
// Retrieve memory information in MiB.
size_t GetTotalVirtualMemory();
// Retrieve amount of physical memory installed on the system in KiB
// units.
- LongLong GetHostMemoryTotal();
+ long long GetHostMemoryTotal();
// Get total system RAM in units of KiB available colectivley to all
// processes in a process group. An example of a process group
// parallel. The amount of memory reported may differ from the host
// total if a host wide resource limit is applied. Such reource limits
// are reported to us via an application specified environment variable.
- LongLong GetHostMemoryAvailable(const char* hostLimitEnvVarName = nullptr);
+ long long GetHostMemoryAvailable(const char* hostLimitEnvVarName = nullptr);
// Get total system RAM in units of KiB available to this process.
// This may differ from the host available if a per-process resource
// system via rlimit API. Resource limits that are not imposed via
// rlimit API may be reported to us via an application specified
// environment variable.
- LongLong GetProcMemoryAvailable(const char* hostLimitEnvVarName = nullptr,
- const char* procLimitEnvVarName = nullptr);
+ long long GetProcMemoryAvailable(const char* hostLimitEnvVarName = nullptr,
+ const char* procLimitEnvVarName = nullptr);
// Get the system RAM used by all processes on the host, in units of KiB.
- LongLong GetHostMemoryUsed();
+ long long GetHostMemoryUsed();
// Get system RAM used by this process id in units of KiB.
- LongLong GetProcMemoryUsed();
+ long long GetProcMemoryUsed();
// Return the load average of the machine or -0.0 if it cannot
// be determined.
# define _XOPEN_SOURCE_EXTENDED
#endif
-#if defined(_WIN32) && \
- (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || \
- defined(__MINGW32__))
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__MINGW32__))
# define KWSYS_WINDOWS_DIRS
#else
# if defined(__SUNPRO_CC)
#include KWSYS_HEADER(Encoding.h)
#include KWSYS_HEADER(Encoding.hxx)
+#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
# pragma set woff 1375 /* base class destructor not virtual */
#endif
-#include <ctype.h>
-#include <errno.h>
+#include <cctype>
+#include <cerrno>
#ifdef __QNX__
# include <malloc.h> /* for malloc/free on QNX */
#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
#if defined(_WIN32) && !defined(_MSC_VER) && defined(__GNUC__)
# include <strings.h> /* for strcasecmp */
#endif
#ifdef _MSC_VER
-# define umask _umask // Note this is still umask on Borland
+# define umask _umask
#endif
// support for realpath call
#ifndef _WIN32
-# include <limits.h>
+# include <climits>
# include <pwd.h>
# include <sys/ioctl.h>
# include <sys/time.h>
# include <sys/param.h>
# include <termios.h>
# endif
-# include <signal.h> /* sigprocmask */
+# include <csignal> /* sigprocmask */
#endif
#ifdef __linux
# if defined(_MSC_VER) && _MSC_VER >= 1800
# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
# endif
-#elif defined(__CYGWIN__)
-# include <windows.h>
-# undef _WIN32
#endif
#if !KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
extern char** environ;
#endif
-#ifdef __CYGWIN__
-# include <sys/cygwin.h>
-#endif
-
// getpwnam doesn't exist on Windows and Cray Xt3/Catamount
// same for TIOCGWINSZ
#if defined(_WIN32) || defined(__LIBCATAMOUNT__) || \
}
#endif
-#if defined(_WIN32) && \
- (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || \
- defined(__MINGW32__))
+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__MINGW32__))
# include <direct.h>
# include <io.h>
# define _unlink unlink
#else
# define KWSYS_SYSTEMTOOLS_MAXPATH 16384
#endif
-#if defined(__WATCOMC__)
-# include <direct.h>
-# define _mkdir mkdir
-# define _rmdir rmdir
-# define _getcwd getcwd
-# define _chdir chdir
-#endif
#if defined(__BEOS__) && !defined(__ZETA__)
# include <be/kernel/OS.h>
}
inline int Chdir(const std::string& dir)
{
-# if defined(__BORLANDC__)
- return chdir(dir.c_str());
-# else
return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
-# endif
}
inline void Realpath(const std::string& path, std::string& resolved_path,
std::string* errorMessage = 0)
bool no_system_path = false);
};
+// Do NOT initialize. Default initialization to zero is necessary.
+static SystemToolsStatic* SystemToolsStatics;
+
#ifdef _WIN32
std::string SystemToolsStatic::GetCasePathName(std::string const& pathIn)
{
{
// Check to see if actual case has already been called
// for this path, and the result is stored in the PathCaseMap
- auto& pcm = SystemTools::Statics->PathCaseMap;
+ auto& pcm = SystemToolsStatics->PathCaseMap;
{
auto itr = pcm.find(p);
if (itr != pcm.end()) {
{
std::string env;
if (SystemTools::GetEnv(key, env)) {
- std::string& menv = SystemTools::Statics->EnvMap[key];
+ std::string& menv = SystemToolsStatics->EnvMap[key];
if (menv != env) {
menv = std::move(env);
}
FILE* SystemTools::Fopen(const std::string& file, const char* mode)
{
#ifdef _WIN32
+ // Remove any 'e', which is supported on UNIX, but not Windows.
+ std::wstring trimmedMode = Encoding::ToWide(mode);
+ trimmedMode.erase(std::remove(trimmedMode.begin(), trimmedMode.end(), L'e'),
+ trimmedMode.end());
return _wfopen(Encoding::ToWindowsExtendedPath(file).c_str(),
- Encoding::ToWide(mode).c_str());
+ trimmedMode.c_str());
#else
return fopen(file.c_str(), mode);
#endif
}
topdir = dir;
if (Mkdir(topdir, mode) != 0) {
- // There is a bug in the Borland Run time library which makes MKDIR
- // return EACCES when it should return EEXISTS
// if it is some other error besides directory exists
// then return false
- if ((errno != EEXIST)
-#ifdef __BORLANDC__
- && (errno != EACCES)
-#endif
- ) {
+ if (errno != EEXIST) {
return false;
}
}
if (path.empty()) {
return false;
}
-#if defined(__CYGWIN__)
- // Convert path to native windows path if possible.
- char winpath[MAX_PATH];
- if (SystemTools::PathCygwinToWin32(path.c_str(), winpath)) {
- return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
- }
- struct stat st;
- return lstat(path.c_str(), &st) == 0;
-#elif defined(_WIN32)
+#if defined(_WIN32)
return (GetFileAttributesW(Encoding::ToWindowsExtendedPath(path).c_str()) !=
INVALID_FILE_ATTRIBUTES);
#else
if (filename.empty()) {
return false;
}
-#if defined(__CYGWIN__)
- // Convert filename to native windows path if possible.
- char winpath[MAX_PATH];
- if (SystemTools::PathCygwinToWin32(filename.c_str(), winpath)) {
- return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
- }
- return access(filename.c_str(), R_OK) == 0;
-#elif defined(_WIN32)
+#if defined(_WIN32)
DWORD attr =
GetFileAttributesW(Encoding::ToWindowsExtendedPath(filename).c_str());
if (attr == INVALID_FILE_ATTRIBUTES) {
// long paths, but _wstat64 rejects paths with '?' in them, thinking
// they are wildcards.
std::wstring const& wpath = Encoding::ToWide(path);
-# if defined(__BORLANDC__)
- return _wstati64(wpath.c_str(), buf);
-# else
return _wstat64(wpath.c_str(), buf);
-# endif
#else
return stat(path.c_str(), buf);
#endif
}
-#ifdef __CYGWIN__
-bool SystemTools::PathCygwinToWin32(const char* path, char* win32_path)
-{
- auto itr = SystemTools::Statics->Cyg2Win32Map.find(path);
- if (itr != SystemTools::Statics->Cyg2Win32Map.end()) {
- strncpy(win32_path, itr->second.c_str(), MAX_PATH);
- } else {
- if (cygwin_conv_path(CCP_POSIX_TO_WIN_A, path, win32_path, MAX_PATH) !=
- 0) {
- win32_path[0] = 0;
- }
- SystemTools::Statics->Cyg2Win32Map.insert(
- SystemToolsStatic::StringMap::value_type(path, win32_path));
- }
- return win32_path[0] != 0;
-}
-#endif
-
bool SystemTools::Touch(const std::string& filename, bool create)
{
- if (!SystemTools::PathExists(filename)) {
+ if (!SystemTools::FileExists(filename)) {
if (create) {
FILE* file = Fopen(filename, "a+b");
if (file) {
paths.emplace_back("/");
}
std::string::size_type pos1 = 0;
- std::string::size_type pos2 = path.find(sep, pos1 + 1);
+ std::string::size_type pos2 = path.find(sep, pos1);
while (pos2 != std::string::npos) {
paths.push_back(path.substr(pos1, pos2 - pos1));
pos1 = pos2 + 1;
ret.erase(pos, 1);
}
// escape spaces and () in the path
- if (ret.find_first_of(" ") != std::string::npos) {
+ if (ret.find_first_of(' ') != std::string::npos) {
std::string result;
char lastch = 1;
for (const char* ch = ret.c_str(); *ch != '\0'; ++ch) {
return false;
}
for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
- if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
- strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
+ if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") != 0 &&
+ strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..") != 0) {
std::string fullPath = source;
fullPath += "/";
fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
dir.Load(source);
size_t fileNum;
for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
- if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
- strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..")) {
+ if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") != 0 &&
+ strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), "..") != 0) {
std::string fullPath = source;
fullPath += "/";
fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
for (std::string const& ext : extensions) {
tryPath = name;
tryPath += ext;
- if (SystemTools::FileExists(tryPath, true)) {
+ if (SystemTools::FileIsExecutable(tryPath)) {
return SystemTools::CollapseFullPath(tryPath);
}
}
#endif
// now try just the name
- if (SystemTools::FileExists(name, true)) {
+ if (SystemTools::FileIsExecutable(name)) {
return SystemTools::CollapseFullPath(name);
}
// now construct the path
tryPath = p;
tryPath += name;
tryPath += ext;
- if (SystemTools::FileExists(tryPath, true)) {
+ if (SystemTools::FileIsExecutable(tryPath)) {
return SystemTools::CollapseFullPath(tryPath);
}
}
// now try it without them
tryPath = p;
tryPath += name;
- if (SystemTools::FileExists(tryPath, true)) {
+ if (SystemTools::FileIsExecutable(tryPath)) {
return SystemTools::CollapseFullPath(tryPath);
}
}
}
}
+bool SystemTools::FileIsExecutable(const std::string& name)
+{
+#if defined(_WIN32)
+ return SystemTools::FileExists(name, true);
+#else
+ return !FileIsDirectory(name) && TestFileAccess(name, TEST_FILE_EXECUTE);
+#endif
+}
+
bool SystemTools::FileIsSymlink(const std::string& name)
{
#if defined(_WIN32)
return Chdir(dir);
}
-std::string SystemTools::GetCurrentWorkingDirectory(bool collapse)
+std::string SystemTools::GetCurrentWorkingDirectory()
{
char buf[2048];
const char* cwd = Getcwd(buf, 2048);
std::string path;
if (cwd) {
path = cwd;
- }
- if (collapse) {
- return SystemTools::CollapseFullPath(path);
+ SystemTools::ConvertToUnixSlashes(path);
}
return path;
}
SystemTools::ConvertToUnixSlashes(dir);
if (!SystemTools::FileIsDirectory(dir)) {
- std::string::size_type slashPos = dir.rfind("/");
+ std::string::size_type slashPos = dir.rfind('/');
if (slashPos != std::string::npos) {
file = dir.substr(slashPos + 1);
dir.resize(slashPos);
failures.push_back(self);
SystemTools::ConvertToUnixSlashes(self);
self = SystemTools::FindProgram(self);
- if (!SystemTools::FileExists(self)) {
+ if (!SystemTools::FileIsExecutable(self)) {
if (buildDir) {
std::string intdir = ".";
#ifdef CMAKE_INTDIR
}
}
if (installPrefix) {
- if (!SystemTools::FileExists(self)) {
+ if (!SystemTools::FileIsExecutable(self)) {
failures.push_back(self);
self = installPrefix;
self += "/bin/";
self += exeName;
}
}
- if (!SystemTools::FileExists(self)) {
+ if (!SystemTools::FileIsExecutable(self)) {
failures.push_back(self);
std::ostringstream msg;
msg << "Can not find the command line program ";
return true;
}
-std::string SystemTools::CollapseFullPath(const std::string& in_relative)
-{
- return SystemTools::CollapseFullPath(in_relative, nullptr);
-}
-
#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP
void SystemTools::AddTranslationPath(const std::string& a,
const std::string& b)
path_b += '/';
}
if (!(path_a == path_b)) {
- SystemTools::Statics->TranslationMap.insert(
+ SystemToolsStatics->TranslationMap.insert(
SystemToolsStatic::StringMap::value_type(std::move(path_a),
std::move(path_b)));
}
// In case a file was specified we still have to go through this:
// Now convert any path found in the table back to the one desired:
- for (auto const& pair : SystemTools::Statics->TranslationMap) {
+ for (auto const& pair : SystemToolsStatics->TranslationMap) {
// We need to check of the path is a substring of the other path
if (path.compare(0, pair.first.size(), pair.first) == 0) {
path = path.replace(0, pair.first.size(), pair.second);
}
}
-std::string SystemTools::CollapseFullPath(const std::string& in_path,
- const char* in_base)
-{
- // Use the current working directory as a base path.
- char buf[2048];
- const char* res_in_base = in_base;
- if (!res_in_base) {
- if (const char* cwd = Getcwd(buf, 2048)) {
- res_in_base = cwd;
- } else {
- res_in_base = "";
- }
- }
+namespace {
- return SystemTools::CollapseFullPath(in_path, std::string(res_in_base));
-}
-
-std::string SystemTools::CollapseFullPath(const std::string& in_path,
- const std::string& in_base)
+std::string CollapseFullPathImpl(std::string const& in_path,
+ std::string const* in_base)
{
// Collect the output path components.
std::vector<std::string> out_components;
// If the input path is relative, start with a base path.
if (path_components[0].empty()) {
std::vector<std::string> base_components;
- // Use the given base path.
- SystemTools::SplitPath(in_base, base_components);
+
+ if (in_base) {
+ // Use the given base path.
+ SystemTools::SplitPath(*in_base, base_components);
+ } else {
+ // Use the current working directory as a base path.
+ std::string cwd = SystemTools::GetCurrentWorkingDirectory();
+ SystemTools::SplitPath(cwd, base_components);
+ }
// Append base path components to the output path.
out_components.push_back(base_components[0]);
SystemTools::CheckTranslationPath(newPath);
#endif
#ifdef _WIN32
- newPath = SystemTools::Statics->GetActualCaseForPathCached(newPath);
+ newPath = SystemToolsStatics->GetActualCaseForPathCached(newPath);
SystemTools::ConvertToUnixSlashes(newPath);
#endif
// Return the reconstructed path.
return newPath;
}
+}
+
+std::string SystemTools::CollapseFullPath(std::string const& in_path)
+{
+ return CollapseFullPathImpl(in_path, nullptr);
+}
+
+std::string SystemTools::CollapseFullPath(std::string const& in_path,
+ const char* in_base)
+{
+ if (!in_base) {
+ return CollapseFullPathImpl(in_path, nullptr);
+ }
+ std::string tmp_base = in_base;
+ return CollapseFullPathImpl(in_path, &tmp_base);
+}
+
+std::string SystemTools::CollapseFullPath(std::string const& in_path,
+ std::string const& in_base)
+{
+ return CollapseFullPathImpl(in_path, &in_base);
+}
// compute the relative path from here to there
std::string SystemTools::RelativePath(const std::string& local,
std::string fn = filename;
SystemTools::ConvertToUnixSlashes(fn);
- std::string::size_type slash_pos = fn.rfind("/");
+ std::string::size_type slash_pos = fn.rfind('/');
if (slash_pos == 0) {
return "/";
}
}
// ----------------------------------------------------------------------
-// These must NOT be initialized. Default initialization to zero is
-// necessary.
+// Do NOT initialize. Default initialization to zero is necessary.
static unsigned int SystemToolsManagerCount;
-SystemToolsStatic* SystemTools::Statics;
// SystemToolsManager manages the SystemTools singleton.
// SystemToolsManager should be included in any translation unit
#endif
// Create statics singleton instance
- SystemTools::Statics = new SystemToolsStatic;
+ SystemToolsStatics = new SystemToolsStatic;
#if KWSYS_SYSTEMTOOLS_USE_TRANSLATION_MAP
// Add some special translation paths for unix. These are not added
void SystemTools::ClassFinalize()
{
- delete SystemTools::Statics;
+ delete SystemToolsStatics;
}
} // namespace KWSYS_NAMESPACE
// combined using the | operator.
typedef int TestFilePermissions;
#if defined(_WIN32) && !defined(__CYGWIN__)
-// On Windows (VC and Borland), no system header defines these constants...
+// On Windows (VC), no system header defines these constants...
static const TestFilePermissions TEST_FILE_OK = 0;
static const TestFilePermissions TEST_FILE_READ = 4;
static const TestFilePermissions TEST_FILE_WRITE = 2;
* Cross platform wrapper for stat struct
*/
#if defined(_WIN32) && !defined(__CYGWIN__)
-# if defined(__BORLANDC__)
- typedef struct stati64 Stat_t;
-# else
typedef struct _stat64 Stat_t;
-# endif
#else
typedef struct stat Stat_t;
#endif
static int Stat(const char* path, Stat_t* buf);
static int Stat(const std::string& path, Stat_t* buf);
-/**
- * Converts Cygwin path to Win32 path. Uses dictionary container for
- * caching and calls to cygwin_conv_to_win32_path from Cygwin dll
- * for actual translation. Returns true on success, else false.
- */
-#ifdef __CYGWIN__
- static bool PathCygwinToWin32(const char* path, char* win32_path);
-#endif
-
/**
* Return file length
*/
* (which defaults to the current working directory). The full path
* is returned.
*/
- static std::string CollapseFullPath(const std::string& in_relative);
- static std::string CollapseFullPath(const std::string& in_relative,
+ static std::string CollapseFullPath(std::string const& in_path);
+ static std::string CollapseFullPath(std::string const& in_path,
const char* in_base);
- static std::string CollapseFullPath(const std::string& in_relative,
- const std::string& in_base);
+ static std::string CollapseFullPath(std::string const& in_path,
+ std::string const& in_base);
/**
* Get the real path for a given path, removing all symlinks. In
*/
/**
- * Open a file considering unicode.
+ * Open a file considering unicode. On Windows, if 'e' is present in
+ * mode it is first discarded.
*/
static FILE* Fopen(const std::string& file, const char* mode);
/**
- * Visual C++ does not define mode_t (note that Borland does, however).
+ * Visual C++ does not define mode_t.
*/
#if defined(_MSC_VER)
typedef unsigned short mode_t;
*/
static bool FileIsDirectory(const std::string& name);
+ /**
+ * Return true if the file is an executable
+ */
+ static bool FileIsExecutable(const std::string& name);
+
/**
* Return true if the file is a symlink
*/
/**
* Get current working directory CWD
*/
- static std::string GetCurrentWorkingDirectory(bool collapse = true);
+ static std::string GetCurrentWorkingDirectory();
/**
* Change directory to the directory specified
return &SystemToolsManagerInstance;
}
- static SystemToolsStatic* Statics;
friend class SystemToolsStatic;
friend class SystemToolsManager;
};
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-/*
- * Copyright (c) 1996
- * Silicon Graphics Computer Systems, Inc.
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Silicon Graphics makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- *
- * Copyright (c) 1994
- * Hewlett-Packard Company
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Hewlett-Packard Company makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-#ifndef @KWSYS_NAMESPACE@_hash_fun_hxx
-#define @KWSYS_NAMESPACE@_hash_fun_hxx
-
-#include <@KWSYS_NAMESPACE@/Configure.hxx>
-
-#include <stddef.h> // size_t
-#include <string>
-
-namespace @KWSYS_NAMESPACE@ {
-
-template <class _Key>
-struct hash
-{
-};
-
-inline size_t _stl_hash_string(const char* __s)
-{
- unsigned long __h = 0;
- for (; *__s; ++__s)
- __h = 5 * __h + *__s;
-
- return size_t(__h);
-}
-
-template <>
-struct hash<char*>
-{
- size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
-};
-
-template <>
-struct hash<const char*>
-{
- size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
-};
-
-template <>
-struct hash<std::string>
-{
- size_t operator()(const std::string& __s) const
- {
- return _stl_hash_string(__s.c_str());
- }
-};
-
-#if !defined(__BORLANDC__)
-template <>
-struct hash<const std::string>
-{
- size_t operator()(const std::string& __s) const
- {
- return _stl_hash_string(__s.c_str());
- }
-};
-#endif
-
-template <>
-struct hash<char>
-{
- size_t operator()(char __x) const { return __x; }
-};
-
-template <>
-struct hash<unsigned char>
-{
- size_t operator()(unsigned char __x) const { return __x; }
-};
-
-template <>
-struct hash<signed char>
-{
- size_t operator()(unsigned char __x) const { return __x; }
-};
-
-template <>
-struct hash<short>
-{
- size_t operator()(short __x) const { return __x; }
-};
-
-template <>
-struct hash<unsigned short>
-{
- size_t operator()(unsigned short __x) const { return __x; }
-};
-
-template <>
-struct hash<int>
-{
- size_t operator()(int __x) const { return __x; }
-};
-
-template <>
-struct hash<unsigned int>
-{
- size_t operator()(unsigned int __x) const { return __x; }
-};
-
-template <>
-struct hash<long>
-{
- size_t operator()(long __x) const { return __x; }
-};
-
-template <>
-struct hash<unsigned long>
-{
- size_t operator()(unsigned long __x) const { return __x; }
-};
-
-// use long long or __int64
-#if @KWSYS_USE_LONG_LONG@
-template <>
-struct hash<long long>
-{
- size_t operator()(long long __x) const { return __x; }
-};
-
-template <>
-struct hash<unsigned long long>
-{
- size_t operator()(unsigned long long __x) const { return __x; }
-};
-#elif @KWSYS_USE___INT64@
-template <>
-struct hash<__int64>
-{
- size_t operator()(__int64 __x) const { return __x; }
-};
-template <>
-struct hash<unsigned __int64>
-{
- size_t operator()(unsigned __int64 __x) const { return __x; }
-};
-#endif // use long long or __int64
-
-} // namespace @KWSYS_NAMESPACE@
-
-#endif
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-/*
- * Copyright (c) 1996
- * Silicon Graphics Computer Systems, Inc.
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Silicon Graphics makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- *
- * Copyright (c) 1994
- * Hewlett-Packard Company
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Hewlett-Packard Company makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-#ifndef @KWSYS_NAMESPACE@_hash_map_hxx
-#define @KWSYS_NAMESPACE@_hash_map_hxx
-
-#include <@KWSYS_NAMESPACE@/hashtable.hxx>
-
-#include <@KWSYS_NAMESPACE@/hash_fun.hxx>
-
-#include <functional> // equal_to
-
-#if defined(_MSC_VER)
-# pragma warning(push)
-# pragma warning(disable : 4284)
-# pragma warning(disable : 4786)
-#endif
-
-#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma set woff 1174
-# pragma set woff 1375
-#endif
-
-namespace @KWSYS_NAMESPACE@ {
-
-// select1st is an extension: it is not part of the standard.
-template <class T1, class T2>
-struct hash_select1st
-{
- const T1& operator()(const std::pair<T1, T2>& __x) const
- {
- return __x.first;
- }
-};
-
-// Forward declaration of equality operator; needed for friend declaration.
-
-template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
- class _EqualKey = std::equal_to<_Key>,
- class _Alloc = std::allocator<char> >
-class hash_map;
-
-template <class _Key, class _Tp, class _HashFn, class _EqKey, class _Alloc>
-bool operator==(const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&,
- const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&);
-
-template <class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
-class hash_map
-{
-private:
- typedef hashtable<std::pair<const _Key, _Tp>, _Key, _HashFcn,
- hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
- _Ht;
- _Ht _M_ht;
-
-public:
- typedef typename _Ht::key_type key_type;
- typedef _Tp data_type;
- typedef _Tp mapped_type;
- typedef typename _Ht::value_type value_type;
- typedef typename _Ht::hasher hasher;
- typedef typename _Ht::key_equal key_equal;
-
- typedef typename _Ht::size_type size_type;
- typedef typename _Ht::difference_type difference_type;
- typedef typename _Ht::pointer pointer;
- typedef typename _Ht::const_pointer const_pointer;
- typedef typename _Ht::reference reference;
- typedef typename _Ht::const_reference const_reference;
-
- typedef typename _Ht::iterator iterator;
- typedef typename _Ht::const_iterator const_iterator;
-
- typedef typename _Ht::allocator_type allocator_type;
-
- hasher hash_funct() const { return _M_ht.hash_funct(); }
- key_equal key_eq() const { return _M_ht.key_eq(); }
- allocator_type get_allocator() const { return _M_ht.get_allocator(); }
-
-public:
- hash_map()
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- }
- explicit hash_map(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- }
- hash_map(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- }
- hash_map(size_type __n, const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- }
-
- template <class _InputIterator>
- hash_map(_InputIterator __f, _InputIterator __l)
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_unique(__f, __l);
- }
- template <class _InputIterator>
- hash_map(_InputIterator __f, _InputIterator __l, size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_unique(__f, __l);
- }
- template <class _InputIterator>
- hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- _M_ht.insert_unique(__f, __l);
- }
- template <class _InputIterator>
- hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- _M_ht.insert_unique(__f, __l);
- }
-
-public:
- size_type size() const { return _M_ht.size(); }
- size_type max_size() const { return _M_ht.max_size(); }
- bool empty() const { return _M_ht.empty(); }
- void swap(hash_map& __hs) { _M_ht.swap(__hs._M_ht); }
-
- friend bool operator==<>(const hash_map&, const hash_map&);
-
- iterator begin() { return _M_ht.begin(); }
- iterator end() { return _M_ht.end(); }
- const_iterator begin() const { return _M_ht.begin(); }
- const_iterator end() const { return _M_ht.end(); }
-
-public:
- std::pair<iterator, bool> insert(const value_type& __obj)
- {
- return _M_ht.insert_unique(__obj);
- }
- template <class _InputIterator>
- void insert(_InputIterator __f, _InputIterator __l)
- {
- _M_ht.insert_unique(__f, __l);
- }
- std::pair<iterator, bool> insert_noresize(const value_type& __obj)
- {
- return _M_ht.insert_unique_noresize(__obj);
- }
-
- iterator find(const key_type& __key) { return _M_ht.find(__key); }
- const_iterator find(const key_type& __key) const
- {
- return _M_ht.find(__key);
- }
-
- _Tp& operator[](const key_type& __key)
- {
- return _M_ht.find_or_insert(value_type(__key, _Tp())).second;
- }
-
- size_type count(const key_type& __key) const { return _M_ht.count(__key); }
-
- std::pair<iterator, iterator> equal_range(const key_type& __key)
- {
- return _M_ht.equal_range(__key);
- }
- std::pair<const_iterator, const_iterator> equal_range(
- const key_type& __key) const
- {
- return _M_ht.equal_range(__key);
- }
-
- size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
- void erase(iterator __it) { _M_ht.erase(__it); }
- void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
- void clear() { _M_ht.clear(); }
-
- void resize(size_type __hint) { _M_ht.resize(__hint); }
- size_type bucket_count() const { return _M_ht.bucket_count(); }
- size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
- size_type elems_in_bucket(size_type __n) const
- {
- return _M_ht.elems_in_bucket(__n);
- }
-};
-
-template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-bool operator==(const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
- const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
-{
- return __hm1._M_ht == __hm2._M_ht;
-}
-
-template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline bool operator!=(
- const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
- const hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
-{
- return !(__hm1 == __hm2);
-}
-
-template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline void swap(hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
- hash_map<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
-{
- __hm1.swap(__hm2);
-}
-
-// Forward declaration of equality operator; needed for friend declaration.
-
-template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
- class _EqualKey = std::equal_to<_Key>,
- class _Alloc = std::allocator<char> >
-class hash_multimap;
-
-template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
- const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2);
-
-template <class _Key, class _Tp, class _HashFcn, class _EqualKey, class _Alloc>
-class hash_multimap
-{
-private:
- typedef hashtable<std::pair<const _Key, _Tp>, _Key, _HashFcn,
- hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
- _Ht;
- _Ht _M_ht;
-
-public:
- typedef typename _Ht::key_type key_type;
- typedef _Tp data_type;
- typedef _Tp mapped_type;
- typedef typename _Ht::value_type value_type;
- typedef typename _Ht::hasher hasher;
- typedef typename _Ht::key_equal key_equal;
-
- typedef typename _Ht::size_type size_type;
- typedef typename _Ht::difference_type difference_type;
- typedef typename _Ht::pointer pointer;
- typedef typename _Ht::const_pointer const_pointer;
- typedef typename _Ht::reference reference;
- typedef typename _Ht::const_reference const_reference;
-
- typedef typename _Ht::iterator iterator;
- typedef typename _Ht::const_iterator const_iterator;
-
- typedef typename _Ht::allocator_type allocator_type;
-
- hasher hash_funct() const { return _M_ht.hash_funct(); }
- key_equal key_eq() const { return _M_ht.key_eq(); }
- allocator_type get_allocator() const { return _M_ht.get_allocator(); }
-
-public:
- hash_multimap()
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- }
- explicit hash_multimap(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- }
- hash_multimap(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- }
- hash_multimap(size_type __n, const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- }
-
- template <class _InputIterator>
- hash_multimap(_InputIterator __f, _InputIterator __l)
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_equal(__f, __l);
- }
- template <class _InputIterator>
- hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_equal(__f, __l);
- }
- template <class _InputIterator>
- hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- _M_ht.insert_equal(__f, __l);
- }
- template <class _InputIterator>
- hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- _M_ht.insert_equal(__f, __l);
- }
-
-public:
- size_type size() const { return _M_ht.size(); }
- size_type max_size() const { return _M_ht.max_size(); }
- bool empty() const { return _M_ht.empty(); }
- void swap(hash_multimap& __hs) { _M_ht.swap(__hs._M_ht); }
-
- friend bool operator==<>(const hash_multimap&, const hash_multimap&);
-
- iterator begin() { return _M_ht.begin(); }
- iterator end() { return _M_ht.end(); }
- const_iterator begin() const { return _M_ht.begin(); }
- const_iterator end() const { return _M_ht.end(); }
-
-public:
- iterator insert(const value_type& __obj)
- {
- return _M_ht.insert_equal(__obj);
- }
- template <class _InputIterator>
- void insert(_InputIterator __f, _InputIterator __l)
- {
- _M_ht.insert_equal(__f, __l);
- }
- iterator insert_noresize(const value_type& __obj)
- {
- return _M_ht.insert_equal_noresize(__obj);
- }
-
- iterator find(const key_type& __key) { return _M_ht.find(__key); }
- const_iterator find(const key_type& __key) const
- {
- return _M_ht.find(__key);
- }
-
- size_type count(const key_type& __key) const { return _M_ht.count(__key); }
-
- std::pair<iterator, iterator> equal_range(const key_type& __key)
- {
- return _M_ht.equal_range(__key);
- }
- std::pair<const_iterator, const_iterator> equal_range(
- const key_type& __key) const
- {
- return _M_ht.equal_range(__key);
- }
-
- size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
- void erase(iterator __it) { _M_ht.erase(__it); }
- void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
- void clear() { _M_ht.clear(); }
-
-public:
- void resize(size_type __hint) { _M_ht.resize(__hint); }
- size_type bucket_count() const { return _M_ht.bucket_count(); }
- size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
- size_type elems_in_bucket(size_type __n) const
- {
- return _M_ht.elems_in_bucket(__n);
- }
-};
-
-template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
- const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2)
-{
- return __hm1._M_ht == __hm2._M_ht;
-}
-
-template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
-inline bool operator!=(
- const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1,
- const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2)
-{
- return !(__hm1 == __hm2);
-}
-
-template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
-inline void swap(hash_multimap<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm1,
- hash_multimap<_Key, _Tp, _HashFcn, _EqlKey, _Alloc>& __hm2)
-{
- __hm1.swap(__hm2);
-}
-
-} // namespace @KWSYS_NAMESPACE@
-
-#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma reset woff 1174
-# pragma reset woff 1375
-#endif
-
-#if defined(_MSC_VER)
-# pragma warning(pop)
-#endif
-
-#endif
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-/*
- * Copyright (c) 1996
- * Silicon Graphics Computer Systems, Inc.
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Silicon Graphics makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- *
- * Copyright (c) 1994
- * Hewlett-Packard Company
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Hewlett-Packard Company makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-#ifndef @KWSYS_NAMESPACE@_hash_set_hxx
-#define @KWSYS_NAMESPACE@_hash_set_hxx
-
-#include <@KWSYS_NAMESPACE@/hashtable.hxx>
-
-#include <@KWSYS_NAMESPACE@/hash_fun.hxx>
-
-#include <functional> // equal_to
-
-#if defined(_MSC_VER)
-# pragma warning(push)
-# pragma warning(disable : 4284)
-# pragma warning(disable : 4786)
-#endif
-
-#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma set woff 1174
-# pragma set woff 1375
-#endif
-
-namespace @KWSYS_NAMESPACE@ {
-
-// identity is an extension: it is not part of the standard.
-template <class _Tp>
-struct _Identity
-{
- const _Tp& operator()(const _Tp& __x) const { return __x; }
-};
-
-// Forward declaration of equality operator; needed for friend declaration.
-
-template <class _Value, class _HashFcn = hash<_Value>,
- class _EqualKey = std::equal_to<_Value>,
- class _Alloc = std::allocator<char> >
-class hash_set;
-
-template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
- const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2);
-
-template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-class hash_set
-{
-private:
- typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey,
- _Alloc>
- _Ht;
- _Ht _M_ht;
-
-public:
- typedef typename _Ht::key_type key_type;
- typedef typename _Ht::value_type value_type;
- typedef typename _Ht::hasher hasher;
- typedef typename _Ht::key_equal key_equal;
-
- typedef typename _Ht::size_type size_type;
- typedef typename _Ht::difference_type difference_type;
- typedef typename _Ht::const_pointer pointer;
- typedef typename _Ht::const_pointer const_pointer;
- typedef typename _Ht::const_reference reference;
- typedef typename _Ht::const_reference const_reference;
-
- typedef typename _Ht::const_iterator iterator;
- typedef typename _Ht::const_iterator const_iterator;
-
- typedef typename _Ht::allocator_type allocator_type;
-
- hasher hash_funct() const { return _M_ht.hash_funct(); }
- key_equal key_eq() const { return _M_ht.key_eq(); }
- allocator_type get_allocator() const { return _M_ht.get_allocator(); }
-
-public:
- hash_set()
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- }
- explicit hash_set(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- }
- hash_set(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- }
- hash_set(size_type __n, const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- }
-
- template <class _InputIterator>
- hash_set(_InputIterator __f, _InputIterator __l)
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_unique(__f, __l);
- }
- template <class _InputIterator>
- hash_set(_InputIterator __f, _InputIterator __l, size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_unique(__f, __l);
- }
- template <class _InputIterator>
- hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- _M_ht.insert_unique(__f, __l);
- }
- template <class _InputIterator>
- hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- _M_ht.insert_unique(__f, __l);
- }
-
-public:
- size_type size() const { return _M_ht.size(); }
- size_type max_size() const { return _M_ht.max_size(); }
- bool empty() const { return _M_ht.empty(); }
- void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); }
-
- friend bool operator==<>(const hash_set&, const hash_set&);
-
- iterator begin() const { return _M_ht.begin(); }
- iterator end() const { return _M_ht.end(); }
-
-public:
- std::pair<iterator, bool> insert(const value_type& __obj)
- {
- typedef typename _Ht::iterator _Ht_iterator;
- std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique(__obj);
- return std::pair<iterator, bool>(__p.first, __p.second);
- }
- template <class _InputIterator>
- void insert(_InputIterator __f, _InputIterator __l)
- {
- _M_ht.insert_unique(__f, __l);
- }
- std::pair<iterator, bool> insert_noresize(const value_type& __obj)
- {
- typedef typename _Ht::iterator _Ht_iterator;
- std::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique_noresize(__obj);
- return std::pair<iterator, bool>(__p.first, __p.second);
- }
-
- iterator find(const key_type& __key) const { return _M_ht.find(__key); }
-
- size_type count(const key_type& __key) const { return _M_ht.count(__key); }
-
- std::pair<iterator, iterator> equal_range(const key_type& __key) const
- {
- return _M_ht.equal_range(__key);
- }
-
- size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
- void erase(iterator __it) { _M_ht.erase(__it); }
- void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
- void clear() { _M_ht.clear(); }
-
-public:
- void resize(size_type __hint) { _M_ht.resize(__hint); }
- size_type bucket_count() const { return _M_ht.bucket_count(); }
- size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
- size_type elems_in_bucket(size_type __n) const
- {
- return _M_ht.elems_in_bucket(__n);
- }
-};
-
-template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
- const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2)
-{
- return __hs1._M_ht == __hs2._M_ht;
-}
-
-template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-inline bool operator!=(
- const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1,
- const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2)
-{
- return !(__hs1 == __hs2);
-}
-
-template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline void swap(hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
- hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
-{
- __hs1.swap(__hs2);
-}
-
-template <class _Value, class _HashFcn = hash<_Value>,
- class _EqualKey = std::equal_to<_Value>,
- class _Alloc = std::allocator<char> >
-class hash_multiset;
-
-template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
- const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2);
-
-template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
-class hash_multiset
-{
-private:
- typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey,
- _Alloc>
- _Ht;
- _Ht _M_ht;
-
-public:
- typedef typename _Ht::key_type key_type;
- typedef typename _Ht::value_type value_type;
- typedef typename _Ht::hasher hasher;
- typedef typename _Ht::key_equal key_equal;
-
- typedef typename _Ht::size_type size_type;
- typedef typename _Ht::difference_type difference_type;
- typedef typename _Ht::const_pointer pointer;
- typedef typename _Ht::const_pointer const_pointer;
- typedef typename _Ht::const_reference reference;
- typedef typename _Ht::const_reference const_reference;
-
- typedef typename _Ht::const_iterator iterator;
- typedef typename _Ht::const_iterator const_iterator;
-
- typedef typename _Ht::allocator_type allocator_type;
-
- hasher hash_funct() const { return _M_ht.hash_funct(); }
- key_equal key_eq() const { return _M_ht.key_eq(); }
- allocator_type get_allocator() const { return _M_ht.get_allocator(); }
-
-public:
- hash_multiset()
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- }
- explicit hash_multiset(size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- }
- hash_multiset(size_type __n, const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- }
- hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- }
-
- template <class _InputIterator>
- hash_multiset(_InputIterator __f, _InputIterator __l)
- : _M_ht(100, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_equal(__f, __l);
- }
- template <class _InputIterator>
- hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n)
- : _M_ht(__n, hasher(), key_equal(), allocator_type())
- {
- _M_ht.insert_equal(__f, __l);
- }
- template <class _InputIterator>
- hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf)
- : _M_ht(__n, __hf, key_equal(), allocator_type())
- {
- _M_ht.insert_equal(__f, __l);
- }
- template <class _InputIterator>
- hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
- const hasher& __hf, const key_equal& __eql,
- const allocator_type& __a = allocator_type())
- : _M_ht(__n, __hf, __eql, __a)
- {
- _M_ht.insert_equal(__f, __l);
- }
-
-public:
- size_type size() const { return _M_ht.size(); }
- size_type max_size() const { return _M_ht.max_size(); }
- bool empty() const { return _M_ht.empty(); }
- void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); }
-
- friend bool operator==<>(const hash_multiset&, const hash_multiset&);
-
- iterator begin() const { return _M_ht.begin(); }
- iterator end() const { return _M_ht.end(); }
-
-public:
- iterator insert(const value_type& __obj)
- {
- return _M_ht.insert_equal(__obj);
- }
- template <class _InputIterator>
- void insert(_InputIterator __f, _InputIterator __l)
- {
- _M_ht.insert_equal(__f, __l);
- }
- iterator insert_noresize(const value_type& __obj)
- {
- return _M_ht.insert_equal_noresize(__obj);
- }
-
- iterator find(const key_type& __key) const { return _M_ht.find(__key); }
-
- size_type count(const key_type& __key) const { return _M_ht.count(__key); }
-
- std::pair<iterator, iterator> equal_range(const key_type& __key) const
- {
- return _M_ht.equal_range(__key);
- }
-
- size_type erase(const key_type& __key) { return _M_ht.erase(__key); }
- void erase(iterator __it) { _M_ht.erase(__it); }
- void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
- void clear() { _M_ht.clear(); }
-
-public:
- void resize(size_type __hint) { _M_ht.resize(__hint); }
- size_type bucket_count() const { return _M_ht.bucket_count(); }
- size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
- size_type elems_in_bucket(size_type __n) const
- {
- return _M_ht.elems_in_bucket(__n);
- }
-};
-
-template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
- const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
-{
- return __hs1._M_ht == __hs2._M_ht;
-}
-
-template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline bool operator!=(
- const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
- const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
-{
- return !(__hs1 == __hs2);
-}
-
-template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
-inline void swap(hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1,
- hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2)
-{
- __hs1.swap(__hs2);
-}
-
-} // namespace @KWSYS_NAMESPACE@
-
-#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
-# pragma reset woff 1174
-# pragma reset woff 1375
-#endif
-
-#if defined(_MSC_VER)
-# pragma warning(pop)
-#endif
-
-#endif
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-/*
- * Copyright (c) 1996
- * Silicon Graphics Computer Systems, Inc.
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Silicon Graphics makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- *
- * Copyright (c) 1994
- * Hewlett-Packard Company
- *
- * Permission to use, copy, modify, distribute and sell this software
- * and its documentation for any purpose is hereby granted without fee,
- * provided that the above copyright notice appear in all copies and
- * that both that copyright notice and this permission notice appear
- * in supporting documentation. Hewlett-Packard Company makes no
- * representations about the suitability of this software for any
- * purpose. It is provided "as is" without express or implied warranty.
- *
- */
-#ifdef __BORLANDC__
-# pragma warn - 8027 /* 'for' not inlined. */
-# pragma warn - 8026 /* 'exception' not inlined. */
-#endif
-
-#ifndef @KWSYS_NAMESPACE@_hashtable_hxx
-# define @KWSYS_NAMESPACE@_hashtable_hxx
-
-# include <@KWSYS_NAMESPACE@/Configure.hxx>
-
-# include <algorithm> // lower_bound
-# include <iterator> // iterator_traits
-# include <memory> // allocator
-# include <stddef.h> // size_t
-# include <utility> // pair
-# include <vector> // vector
-
-# if defined(_MSC_VER)
-# pragma warning(push)
-# pragma warning(disable : 4284)
-# pragma warning(disable : 4786)
-# pragma warning(disable : 4512) /* no assignment operator for class */
-# endif
-# if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 3970 /* pointer to int conversion */ 3321 3968
-# endif
-
-// In C++11, clang will warn about using dynamic exception specifications
-// as they are deprecated. But as this class is trying to faithfully
-// mimic unordered_set and unordered_map, we want to keep the 'throw()'
-// decorations below. So we suppress the warning.
-# if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wdeprecated"
-# endif
-# endif
-
-namespace @KWSYS_NAMESPACE@ {
-
-template <class _Val>
-struct _Hashtable_node
-{
- _Hashtable_node* _M_next;
- _Val _M_val;
- void public_method_to_quiet_warning_about_all_methods_private();
-
-private:
- void operator=(_Hashtable_node<_Val> const&) = delete;
-};
-
-template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
- class _EqualKey, class _Alloc = std::allocator<char> >
-class hashtable;
-
-template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
- class _EqualKey, class _Alloc>
-struct _Hashtable_iterator;
-
-template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
- class _EqualKey, class _Alloc>
-struct _Hashtable_const_iterator;
-
-template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
- class _EqualKey, class _Alloc>
-struct _Hashtable_iterator
-{
- typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>
- _Hashtable;
- typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
- _Alloc>
- iterator;
- typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
- _EqualKey, _Alloc>
- const_iterator;
- typedef _Hashtable_node<_Val> _Node;
-
- typedef std::forward_iterator_tag iterator_category;
- typedef _Val value_type;
- typedef ptrdiff_t difference_type;
- typedef size_t size_type;
- typedef _Val& reference;
- typedef _Val* pointer;
-
- _Node* _M_cur;
- _Hashtable* _M_ht;
-
- _Hashtable_iterator(_Node* __n, _Hashtable* __tab)
- : _M_cur(__n)
- , _M_ht(__tab)
- {
- }
- _Hashtable_iterator() {}
- reference operator*() const { return _M_cur->_M_val; }
- pointer operator->() const { return &(operator*()); }
- iterator& operator++();
- iterator operator++(int);
- bool operator==(const iterator& __it) const { return _M_cur == __it._M_cur; }
- bool operator!=(const iterator& __it) const { return _M_cur != __it._M_cur; }
-};
-
-template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
- class _EqualKey, class _Alloc>
-struct _Hashtable_const_iterator
-{
- typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>
- _Hashtable;
- typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
- _Alloc>
- iterator;
- typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
- _EqualKey, _Alloc>
- const_iterator;
- typedef _Hashtable_node<_Val> _Node;
-
- typedef std::forward_iterator_tag iterator_category;
- typedef _Val value_type;
- typedef ptrdiff_t difference_type;
- typedef size_t size_type;
- typedef const _Val& reference;
- typedef const _Val* pointer;
-
- const _Node* _M_cur;
- const _Hashtable* _M_ht;
-
- _Hashtable_const_iterator(const _Node* __n, const _Hashtable* __tab)
- : _M_cur(__n)
- , _M_ht(__tab)
- {
- }
- _Hashtable_const_iterator() {}
- _Hashtable_const_iterator(const iterator& __it)
- : _M_cur(__it._M_cur)
- , _M_ht(__it._M_ht)
- {
- }
- reference operator*() const { return _M_cur->_M_val; }
- pointer operator->() const { return &(operator*()); }
- const_iterator& operator++();
- const_iterator operator++(int);
- bool operator==(const const_iterator& __it) const
- {
- return _M_cur == __it._M_cur;
- }
- bool operator!=(const const_iterator& __it) const
- {
- return _M_cur != __it._M_cur;
- }
-};
-
-// Note: assumes long is at least 32 bits.
-enum
-{
- _stl_num_primes = 31
-};
-
-// create a function with a static local to that function that returns
-// the static
-static inline const unsigned long* get_stl_prime_list()
-{
-
- static const unsigned long _stl_prime_list[_stl_num_primes] = {
- 5ul, 11ul, 23ul, 53ul, 97ul,
- 193ul, 389ul, 769ul, 1543ul, 3079ul,
- 6151ul, 12289ul, 24593ul, 49157ul, 98317ul,
- 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul,
- 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul,
- 201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul,
- 4294967291ul
- };
-
- return &_stl_prime_list[0];
-}
-
-static inline size_t _stl_next_prime(size_t __n)
-{
- const unsigned long* __first = get_stl_prime_list();
- const unsigned long* __last = get_stl_prime_list() + (int)_stl_num_primes;
- const unsigned long* pos = std::lower_bound(__first, __last, __n);
- return pos == __last ? *(__last - 1) : *pos;
-}
-
-// Forward declaration of operator==.
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-class hashtable;
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
- const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2);
-
-// Hashtables handle allocators a bit differently than other containers
-// do. If we're using standard-conforming allocators, then a hashtable
-// unconditionally has a member variable to hold its allocator, even if
-// it so happens that all instances of the allocator type are identical.
-// This is because, for hashtables, this extra storage is negligible.
-// Additionally, a base class wouldn't serve any other purposes; it
-// wouldn't, for example, simplify the exception-handling code.
-
-template <class _Val, class _Key, class _HashFcn, class _ExtractKey,
- class _EqualKey, class _Alloc>
-class hashtable
-{
-public:
- typedef _Key key_type;
- typedef _Val value_type;
- typedef _HashFcn hasher;
- typedef _EqualKey key_equal;
-
- typedef size_t size_type;
- typedef ptrdiff_t difference_type;
- typedef value_type* pointer;
- typedef const value_type* const_pointer;
- typedef value_type& reference;
- typedef const value_type& const_reference;
-
- hasher hash_funct() const { return _M_hash; }
- key_equal key_eq() const { return _M_equals; }
-
-private:
- typedef _Hashtable_node<_Val> _Node;
-
-public:
- typedef typename _Alloc::template rebind<_Val>::other allocator_type;
- allocator_type get_allocator() const { return _M_node_allocator; }
-
-private:
- typedef
- typename _Alloc::template rebind<_Node>::other _M_node_allocator_type;
- typedef
- typename _Alloc::template rebind<_Node*>::other _M_node_ptr_allocator_type;
- typedef std::vector<_Node*, _M_node_ptr_allocator_type> _M_buckets_type;
-
-private:
- _M_node_allocator_type _M_node_allocator;
- hasher _M_hash;
- key_equal _M_equals;
- _ExtractKey _M_get_key;
- _M_buckets_type _M_buckets;
- size_type _M_num_elements;
-
- _Node* _M_get_node() { return _M_node_allocator.allocate(1); }
- void _M_put_node(_Node* __p) { _M_node_allocator.deallocate(__p, 1); }
-
-public:
- typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey,
- _Alloc>
- iterator;
- typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
- _EqualKey, _Alloc>
- const_iterator;
-
- friend struct _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey,
- _EqualKey, _Alloc>;
- friend struct _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey,
- _EqualKey, _Alloc>;
-
-public:
- hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql,
- const _ExtractKey& __ext,
- const allocator_type& __a = allocator_type())
- : _M_node_allocator(__a)
- , _M_hash(__hf)
- , _M_equals(__eql)
- , _M_get_key(__ext)
- , _M_buckets(__a)
- , _M_num_elements(0)
- {
- _M_initialize_buckets(__n);
- }
-
- hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql,
- const allocator_type& __a = allocator_type())
- : _M_node_allocator(__a)
- , _M_hash(__hf)
- , _M_equals(__eql)
- , _M_get_key(_ExtractKey())
- , _M_buckets(__a)
- , _M_num_elements(0)
- {
- _M_initialize_buckets(__n);
- }
-
- hashtable(const hashtable& __ht)
- : _M_node_allocator(__ht.get_allocator())
- , _M_hash(__ht._M_hash)
- , _M_equals(__ht._M_equals)
- , _M_get_key(__ht._M_get_key)
- , _M_buckets(__ht.get_allocator())
- , _M_num_elements(0)
- {
- _M_copy_from(__ht);
- }
-
- hashtable& operator=(const hashtable& __ht)
- {
- if (&__ht != this) {
- clear();
- _M_hash = __ht._M_hash;
- _M_equals = __ht._M_equals;
- _M_get_key = __ht._M_get_key;
- _M_copy_from(__ht);
- }
- return *this;
- }
-
- ~hashtable() { clear(); }
-
- size_type size() const { return _M_num_elements; }
- size_type max_size() const { return size_type(-1); }
- bool empty() const { return size() == 0; }
-
- void swap(hashtable& __ht)
- {
- std::swap(_M_hash, __ht._M_hash);
- std::swap(_M_equals, __ht._M_equals);
- std::swap(_M_get_key, __ht._M_get_key);
- _M_buckets.swap(__ht._M_buckets);
- std::swap(_M_num_elements, __ht._M_num_elements);
- }
-
- iterator begin()
- {
- for (size_type __n = 0; __n < _M_buckets.size(); ++__n)
- if (_M_buckets[__n])
- return iterator(_M_buckets[__n], this);
- return end();
- }
-
- iterator end() { return iterator(nullptr, this); }
-
- const_iterator begin() const
- {
- for (size_type __n = 0; __n < _M_buckets.size(); ++__n)
- if (_M_buckets[__n])
- return const_iterator(_M_buckets[__n], this);
- return end();
- }
-
- const_iterator end() const { return const_iterator(nullptr, this); }
-
- friend bool operator==<>(const hashtable&, const hashtable&);
-
-public:
- size_type bucket_count() const { return _M_buckets.size(); }
-
- size_type max_bucket_count() const
- {
- return get_stl_prime_list()[(int)_stl_num_primes - 1];
- }
-
- size_type elems_in_bucket(size_type __bucket) const
- {
- size_type __result = 0;
- for (_Node* __cur = _M_buckets[__bucket]; __cur; __cur = __cur->_M_next)
- __result += 1;
- return __result;
- }
-
- std::pair<iterator, bool> insert_unique(const value_type& __obj)
- {
- resize(_M_num_elements + 1);
- return insert_unique_noresize(__obj);
- }
-
- iterator insert_equal(const value_type& __obj)
- {
- resize(_M_num_elements + 1);
- return insert_equal_noresize(__obj);
- }
-
- std::pair<iterator, bool> insert_unique_noresize(const value_type& __obj);
- iterator insert_equal_noresize(const value_type& __obj);
-
- template <class _InputIterator>
- void insert_unique(_InputIterator __f, _InputIterator __l)
- {
- insert_unique(
- __f, __l,
- typename std::iterator_traits<_InputIterator>::iterator_category());
- }
-
- template <class _InputIterator>
- void insert_equal(_InputIterator __f, _InputIterator __l)
- {
- insert_equal(
- __f, __l,
- typename std::iterator_traits<_InputIterator>::iterator_category());
- }
-
- template <class _InputIterator>
- void insert_unique(_InputIterator __f, _InputIterator __l,
- std::input_iterator_tag)
- {
- for (; __f != __l; ++__f)
- insert_unique(*__f);
- }
-
- template <class _InputIterator>
- void insert_equal(_InputIterator __f, _InputIterator __l,
- std::input_iterator_tag)
- {
- for (; __f != __l; ++__f)
- insert_equal(*__f);
- }
-
- template <class _ForwardIterator>
- void insert_unique(_ForwardIterator __f, _ForwardIterator __l,
- std::forward_iterator_tag)
- {
- size_type __n = 0;
- std::distance(__f, __l, __n);
- resize(_M_num_elements + __n);
- for (; __n > 0; --__n, ++__f)
- insert_unique_noresize(*__f);
- }
-
- template <class _ForwardIterator>
- void insert_equal(_ForwardIterator __f, _ForwardIterator __l,
- std::forward_iterator_tag)
- {
- size_type __n = 0;
- std::distance(__f, __l, __n);
- resize(_M_num_elements + __n);
- for (; __n > 0; --__n, ++__f)
- insert_equal_noresize(*__f);
- }
-
- reference find_or_insert(const value_type& __obj);
-
- iterator find(const key_type& __key)
- {
- size_type __n = _M_bkt_num_key(__key);
- _Node* __first;
- for (__first = _M_buckets[__n];
- __first && !_M_equals(_M_get_key(__first->_M_val), __key);
- __first = __first->_M_next) {
- }
- return iterator(__first, this);
- }
-
- const_iterator find(const key_type& __key) const
- {
- size_type __n = _M_bkt_num_key(__key);
- const _Node* __first;
- for (__first = _M_buckets[__n];
- __first && !_M_equals(_M_get_key(__first->_M_val), __key);
- __first = __first->_M_next) {
- }
- return const_iterator(__first, this);
- }
-
- size_type count(const key_type& __key) const
- {
- const size_type __n = _M_bkt_num_key(__key);
- size_type __result = 0;
-
- for (const _Node* __cur = _M_buckets[__n]; __cur; __cur = __cur->_M_next)
- if (_M_equals(_M_get_key(__cur->_M_val), __key))
- ++__result;
- return __result;
- }
-
- std::pair<iterator, iterator> equal_range(const key_type& __key);
-
- std::pair<const_iterator, const_iterator> equal_range(
- const key_type& __key) const;
-
- size_type erase(const key_type& __key);
- void erase(const iterator& __it);
- void erase(iterator __first, iterator __last);
-
- void erase(const const_iterator& __it);
- void erase(const_iterator __first, const_iterator __last);
-
- void resize(size_type __num_elements_hint);
- void clear();
-
-private:
- size_type _M_next_size(size_type __n) const { return _stl_next_prime(__n); }
-
- void _M_initialize_buckets(size_type __n)
- {
- const size_type __n_buckets = _M_next_size(__n);
- _M_buckets.reserve(__n_buckets);
- _M_buckets.insert(_M_buckets.end(), __n_buckets, (_Node*)nullptr);
- _M_num_elements = 0;
- }
-
- size_type _M_bkt_num_key(const key_type& __key) const
- {
- return _M_bkt_num_key(__key, _M_buckets.size());
- }
-
- size_type _M_bkt_num(const value_type& __obj) const
- {
- return _M_bkt_num_key(_M_get_key(__obj));
- }
-
- size_type _M_bkt_num_key(const key_type& __key, size_t __n) const
- {
- return _M_hash(__key) % __n;
- }
-
- size_type _M_bkt_num(const value_type& __obj, size_t __n) const
- {
- return _M_bkt_num_key(_M_get_key(__obj), __n);
- }
-
- void construct(_Val* p, const _Val& v) { new (p) _Val(v); }
- void destroy(_Val* p)
- {
- (void)p;
- p->~_Val();
- }
-
- _Node* _M_new_node(const value_type& __obj)
- {
- _Node* __n = _M_get_node();
- __n->_M_next = nullptr;
- try {
- construct(&__n->_M_val, __obj);
- return __n;
- } catch (...) {
- _M_put_node(__n);
- throw;
- }
- }
-
- void _M_delete_node(_Node* __n)
- {
- destroy(&__n->_M_val);
- _M_put_node(__n);
- }
-
- void _M_erase_bucket(const size_type __n, _Node* __first, _Node* __last);
- void _M_erase_bucket(const size_type __n, _Node* __last);
-
- void _M_copy_from(const hashtable& __ht);
-};
-
-template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
- class _All>
-_Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>&
-_Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++()
-{
- const _Node* __old = _M_cur;
- _M_cur = _M_cur->_M_next;
- if (!_M_cur) {
- size_type __bucket = _M_ht->_M_bkt_num(__old->_M_val);
- while (!_M_cur && ++__bucket < _M_ht->_M_buckets.size())
- _M_cur = _M_ht->_M_buckets[__bucket];
- }
- return *this;
-}
-
-template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
- class _All>
-inline _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>
-_Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++(int)
-{
- iterator __tmp = *this;
- ++*this;
- return __tmp;
-}
-
-template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
- class _All>
-_Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>&
-_Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++()
-{
- const _Node* __old = _M_cur;
- _M_cur = _M_cur->_M_next;
- if (!_M_cur) {
- size_type __bucket = _M_ht->_M_bkt_num(__old->_M_val);
- while (!_M_cur && ++__bucket < _M_ht->_M_buckets.size())
- _M_cur = _M_ht->_M_buckets[__bucket];
- }
- return *this;
-}
-
-template <class _Val, class _Key, class _HF, class _ExK, class _EqK,
- class _All>
-inline _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>
-_Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>::operator++(int)
-{
- const_iterator __tmp = *this;
- ++*this;
- return __tmp;
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
- const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2)
-{
- typedef typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_Node _Node;
- if (__ht1._M_buckets.size() != __ht2._M_buckets.size())
- return false;
- for (int __n = 0; __n < __ht1._M_buckets.size(); ++__n) {
- _Node* __cur1 = __ht1._M_buckets[__n];
- _Node* __cur2 = __ht2._M_buckets[__n];
- for (; __cur1 && __cur2 && __cur1->_M_val == __cur2->_M_val;
- __cur1 = __cur1->_M_next, __cur2 = __cur2->_M_next) {
- }
- if (__cur1 || __cur2)
- return false;
- }
- return true;
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline bool operator!=(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1,
- const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2)
-{
- return !(__ht1 == __ht2);
-}
-
-template <class _Val, class _Key, class _HF, class _Extract, class _EqKey,
- class _All>
-inline void swap(hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht1,
- hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht2)
-{
- __ht1.swap(__ht2);
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator, bool>
-hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::insert_unique_noresize(
- const value_type& __obj)
-{
- const size_type __n = _M_bkt_num(__obj);
- _Node* __first = _M_buckets[__n];
-
- for (_Node* __cur = __first; __cur; __cur = __cur->_M_next)
- if (_M_equals(_M_get_key(__cur->_M_val), _M_get_key(__obj)))
- return std::pair<iterator, bool>(iterator(__cur, this), false);
-
- _Node* __tmp = _M_new_node(__obj);
- __tmp->_M_next = __first;
- _M_buckets[__n] = __tmp;
- ++_M_num_elements;
- return std::pair<iterator, bool>(iterator(__tmp, this), true);
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator
-hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::insert_equal_noresize(
- const value_type& __obj)
-{
- const size_type __n = _M_bkt_num(__obj);
- _Node* __first = _M_buckets[__n];
-
- for (_Node* __cur = __first; __cur; __cur = __cur->_M_next)
- if (_M_equals(_M_get_key(__cur->_M_val), _M_get_key(__obj))) {
- _Node* __tmp = _M_new_node(__obj);
- __tmp->_M_next = __cur->_M_next;
- __cur->_M_next = __tmp;
- ++_M_num_elements;
- return iterator(__tmp, this);
- }
-
- _Node* __tmp = _M_new_node(__obj);
- __tmp->_M_next = __first;
- _M_buckets[__n] = __tmp;
- ++_M_num_elements;
- return iterator(__tmp, this);
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::reference
-hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::find_or_insert(
- const value_type& __obj)
-{
- resize(_M_num_elements + 1);
-
- size_type __n = _M_bkt_num(__obj);
- _Node* __first = _M_buckets[__n];
-
- for (_Node* __cur = __first; __cur; __cur = __cur->_M_next)
- if (_M_equals(_M_get_key(__cur->_M_val), _M_get_key(__obj)))
- return __cur->_M_val;
-
- _Node* __tmp = _M_new_node(__obj);
- __tmp->_M_next = __first;
- _M_buckets[__n] = __tmp;
- ++_M_num_elements;
- return __tmp->_M_val;
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator,
- typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator>
-hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::equal_range(const key_type& __key)
-{
- typedef std::pair<iterator, iterator> _Pii;
- const size_type __n = _M_bkt_num_key(__key);
-
- for (_Node* __first = _M_buckets[__n]; __first; __first = __first->_M_next)
- if (_M_equals(_M_get_key(__first->_M_val), __key)) {
- for (_Node* __cur = __first->_M_next; __cur; __cur = __cur->_M_next)
- if (!_M_equals(_M_get_key(__cur->_M_val), __key))
- return _Pii(iterator(__first, this), iterator(__cur, this));
- for (size_type __m = __n + 1; __m < _M_buckets.size(); ++__m)
- if (_M_buckets[__m])
- return _Pii(iterator(__first, this),
- iterator(_M_buckets[__m], this));
- return _Pii(iterator(__first, this), end());
- }
- return _Pii(end(), end());
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-std::pair<typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator,
- typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator>
-hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::equal_range(
- const key_type& __key) const
-{
- typedef std::pair<const_iterator, const_iterator> _Pii;
- const size_type __n = _M_bkt_num_key(__key);
-
- for (const _Node* __first = _M_buckets[__n]; __first;
- __first = __first->_M_next) {
- if (_M_equals(_M_get_key(__first->_M_val), __key)) {
- for (const _Node* __cur = __first->_M_next; __cur;
- __cur = __cur->_M_next)
- if (!_M_equals(_M_get_key(__cur->_M_val), __key))
- return _Pii(const_iterator(__first, this),
- const_iterator(__cur, this));
- for (size_type __m = __n + 1; __m < _M_buckets.size(); ++__m)
- if (_M_buckets[__m])
- return _Pii(const_iterator(__first, this),
- const_iterator(_M_buckets[__m], this));
- return _Pii(const_iterator(__first, this), end());
- }
- }
- return _Pii(end(), end());
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::size_type
-hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(const key_type& __key)
-{
- const size_type __n = _M_bkt_num_key(__key);
- _Node* __first = _M_buckets[__n];
- size_type __erased = 0;
-
- if (__first) {
- _Node* __cur = __first;
- _Node* __next = __cur->_M_next;
- while (__next) {
- if (_M_equals(_M_get_key(__next->_M_val), __key)) {
- __cur->_M_next = __next->_M_next;
- _M_delete_node(__next);
- __next = __cur->_M_next;
- ++__erased;
- --_M_num_elements;
- } else {
- __cur = __next;
- __next = __cur->_M_next;
- }
- }
- if (_M_equals(_M_get_key(__first->_M_val), __key)) {
- _M_buckets[__n] = __first->_M_next;
- _M_delete_node(__first);
- ++__erased;
- --_M_num_elements;
- }
- }
- return __erased;
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(const iterator& __it)
-{
- _Node* __p = __it._M_cur;
- if (__p) {
- const size_type __n = _M_bkt_num(__p->_M_val);
- _Node* __cur = _M_buckets[__n];
-
- if (__cur == __p) {
- _M_buckets[__n] = __cur->_M_next;
- _M_delete_node(__cur);
- --_M_num_elements;
- } else {
- _Node* __next = __cur->_M_next;
- while (__next) {
- if (__next == __p) {
- __cur->_M_next = __next->_M_next;
- _M_delete_node(__next);
- --_M_num_elements;
- break;
- } else {
- __cur = __next;
- __next = __cur->_M_next;
- }
- }
- }
- }
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(iterator __first,
- iterator __last)
-{
- size_type __f_bucket =
- __first._M_cur ? _M_bkt_num(__first._M_cur->_M_val) : _M_buckets.size();
- size_type __l_bucket =
- __last._M_cur ? _M_bkt_num(__last._M_cur->_M_val) : _M_buckets.size();
-
- if (__first._M_cur == __last._M_cur)
- return;
- else if (__f_bucket == __l_bucket)
- _M_erase_bucket(__f_bucket, __first._M_cur, __last._M_cur);
- else {
- _M_erase_bucket(__f_bucket, __first._M_cur, nullptr);
- for (size_type __n = __f_bucket + 1; __n < __l_bucket; ++__n)
- _M_erase_bucket(__n, nullptr);
- if (__l_bucket != _M_buckets.size())
- _M_erase_bucket(__l_bucket, __last._M_cur);
- }
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(
- const_iterator __first, const_iterator __last)
-{
- erase(iterator(const_cast<_Node*>(__first._M_cur),
- const_cast<hashtable*>(__first._M_ht)),
- iterator(const_cast<_Node*>(__last._M_cur),
- const_cast<hashtable*>(__last._M_ht)));
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::erase(
- const const_iterator& __it)
-{
- erase(iterator(const_cast<_Node*>(__it._M_cur),
- const_cast<hashtable*>(__it._M_ht)));
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::resize(
- size_type __num_elements_hint)
-{
- const size_type __old_n = _M_buckets.size();
- if (__num_elements_hint > __old_n) {
- const size_type __n = _M_next_size(__num_elements_hint);
- if (__n > __old_n) {
- _M_buckets_type __tmp(__n, (_Node*)(nullptr),
- _M_buckets.get_allocator());
- try {
- for (size_type __bucket = 0; __bucket < __old_n; ++__bucket) {
- _Node* __first = _M_buckets[__bucket];
- while (__first) {
- size_type __new_bucket = _M_bkt_num(__first->_M_val, __n);
- _M_buckets[__bucket] = __first->_M_next;
- __first->_M_next = __tmp[__new_bucket];
- __tmp[__new_bucket] = __first;
- __first = _M_buckets[__bucket];
- }
- }
- _M_buckets.swap(__tmp);
- } catch (...) {
- for (size_type __bucket = 0; __bucket < __tmp.size(); ++__bucket) {
- while (__tmp[__bucket]) {
- _Node* __next = __tmp[__bucket]->_M_next;
- _M_delete_node(__tmp[__bucket]);
- __tmp[__bucket] = __next;
- }
- }
- throw;
- }
- }
- }
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_erase_bucket(
- const size_type __n, _Node* __first, _Node* __last)
-{
- _Node* __cur = _M_buckets[__n];
- if (__cur == __first)
- _M_erase_bucket(__n, __last);
- else {
- _Node* __next;
- for (__next = __cur->_M_next; __next != __first;
- __cur = __next, __next = __cur->_M_next)
- ;
- while (__next != __last) {
- __cur->_M_next = __next->_M_next;
- _M_delete_node(__next);
- __next = __cur->_M_next;
- --_M_num_elements;
- }
- }
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_erase_bucket(
- const size_type __n, _Node* __last)
-{
- _Node* __cur = _M_buckets[__n];
- while (__cur != __last) {
- _Node* __next = __cur->_M_next;
- _M_delete_node(__cur);
- __cur = __next;
- _M_buckets[__n] = __cur;
- --_M_num_elements;
- }
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::clear()
-{
- for (size_type __i = 0; __i < _M_buckets.size(); ++__i) {
- _Node* __cur = _M_buckets[__i];
- while (__cur != nullptr) {
- _Node* __next = __cur->_M_next;
- _M_delete_node(__cur);
- __cur = __next;
- }
- _M_buckets[__i] = nullptr;
- }
- _M_num_elements = 0;
-}
-
-template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All>
-void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_M_copy_from(
- const hashtable& __ht)
-{
- _M_buckets.clear();
- _M_buckets.reserve(__ht._M_buckets.size());
- _M_buckets.insert(_M_buckets.end(), __ht._M_buckets.size(), (_Node*)nullptr);
- try {
- for (size_type __i = 0; __i < __ht._M_buckets.size(); ++__i) {
- const _Node* __cur = __ht._M_buckets[__i];
- if (__cur) {
- _Node* __copy = _M_new_node(__cur->_M_val);
- _M_buckets[__i] = __copy;
-
- for (_Node* __next = __cur->_M_next; __next;
- __cur = __next, __next = __cur->_M_next) {
- __copy->_M_next = _M_new_node(__next->_M_val);
- __copy = __copy->_M_next;
- }
- }
- }
- _M_num_elements = __ht._M_num_elements;
- } catch (...) {
- clear();
- throw;
- }
-}
-
-} // namespace @KWSYS_NAMESPACE@
-
-// Undo warning suppression.
-# if defined(__clang__) && defined(__has_warning)
-# if __has_warning("-Wdeprecated")
-# pragma clang diagnostic pop
-# endif
-# endif
-
-# if defined(_MSC_VER)
-# pragma warning(pop)
-# endif
-
-#endif
return clock_gettime(CLOCK_MONOTONIC, &ts);
}
#endif
-
-#ifdef TEST_KWSYS_C_TYPE_MACROS
-char* info_macros =
-# if defined(__SIZEOF_SHORT__)
- "INFO:macro[__SIZEOF_SHORT__]\n"
-# endif
-# if defined(__SIZEOF_INT__)
- "INFO:macro[__SIZEOF_INT__]\n"
-# endif
-# if defined(__SIZEOF_LONG__)
- "INFO:macro[__SIZEOF_LONG__]\n"
-# endif
-# if defined(__SIZEOF_LONG_LONG__)
- "INFO:macro[__SIZEOF_LONG_LONG__]\n"
-# endif
-# if defined(__SHORT_MAX__)
- "INFO:macro[__SHORT_MAX__]\n"
-# endif
-# if defined(__INT_MAX__)
- "INFO:macro[__INT_MAX__]\n"
-# endif
-# if defined(__LONG_MAX__)
- "INFO:macro[__LONG_MAX__]\n"
-# endif
-# if defined(__LONG_LONG_MAX__)
- "INFO:macro[__LONG_LONG_MAX__]\n"
-# endif
- "";
-
-int KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv)
-{
- int require = 0;
- require += info_macros[argc];
- (void)argv;
- return require;
-}
-#endif
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-#ifdef TEST_KWSYS_CXX_HAS_CSTDIO
-# include <cstdio>
-int main()
-{
- return 0;
-}
-#endif
-
-#ifdef TEST_KWSYS_CXX_HAS_LONG_LONG
-long long f(long long n)
-{
- return n;
-}
-int main()
-{
- long long n = 0;
- return static_cast<int>(f(n));
-}
-#endif
-
-#ifdef TEST_KWSYS_CXX_HAS___INT64
-__int64 f(__int64 n)
-{
- return n;
-}
-int main()
-{
- __int64 n = 0;
- return static_cast<int>(f(n));
-}
-#endif
#ifdef TEST_KWSYS_CXX_STAT_HAS_ST_MTIM
# include <sys/types.h>
}
#endif
-#ifdef TEST_KWSYS_CXX_SAME_LONG_AND___INT64
-void function(long**)
-{
-}
-int main()
-{
- __int64** p = 0;
- function(p);
- return 0;
-}
-#endif
-
-#ifdef TEST_KWSYS_CXX_SAME_LONG_LONG_AND___INT64
-void function(long long**)
-{
-}
-int main()
-{
- __int64** p = 0;
- function(p);
- return 0;
-}
-#endif
-
-#ifdef TEST_KWSYS_IOS_HAS_ISTREAM_LONG_LONG
-# include <iostream>
-int test_istream(std::istream& is, long long& x)
-{
- return (is >> x) ? 1 : 0;
-}
-int main()
-{
- long long x = 0;
- return test_istream(std::cin, x);
-}
-#endif
-
-#ifdef TEST_KWSYS_IOS_HAS_OSTREAM_LONG_LONG
-# include <iostream>
-int test_ostream(std::ostream& os, long long x)
-{
- return (os << x) ? 1 : 0;
-}
-int main()
-{
- long long x = 0;
- return test_ostream(std::cout, x);
-}
-#endif
-
-#ifdef TEST_KWSYS_IOS_HAS_ISTREAM___INT64
-# include <iostream>
-int test_istream(std::istream& is, __int64& x)
-{
- return (is >> x) ? 1 : 0;
-}
-int main()
-{
- __int64 x = 0;
- return test_istream(std::cin, x);
-}
-#endif
-
-#ifdef TEST_KWSYS_IOS_HAS_OSTREAM___INT64
-# include <iostream>
-int test_ostream(std::ostream& os, __int64 x)
-{
- return (os << x) ? 1 : 0;
-}
-int main()
-{
- __int64 x = 0;
- return test_ostream(std::cout, x);
-}
-#endif
-
#ifdef TEST_KWSYS_CXX_HAS_SETENV
# include <stdlib.h>
int main()
}
#endif
-#ifdef TEST_KWSYS_CXX_HAS_ATOLL
-# include <stdlib.h>
-int main()
-{
- const char* str = "1024";
- return static_cast<int>(atoll(str));
-}
-#endif
-
-#ifdef TEST_KWSYS_CXX_HAS_ATOL
-# include <stdlib.h>
-int main()
-{
- const char* str = "1024";
- return static_cast<int>(atol(str));
-}
-#endif
-
-#ifdef TEST_KWSYS_CXX_HAS__ATOI64
-# include <stdlib.h>
-int main()
-{
- const char* str = "1024";
- return static_cast<int>(_atoi64(str));
-}
-#endif
-
#ifdef TEST_KWSYS_CXX_HAS_UTIMES
# include <sys/time.h>
int main()
}
#endif
-#ifdef TEST_KWSYS_CXX_HAS_BORLAND_ASM
-int main()
-{
- int a = 1;
- __asm {
- xor EBX, EBX;
- mov a, EBX;
- }
-
- return a;
-}
-#endif
-
-#ifdef TEST_KWSYS_CXX_HAS_BORLAND_ASM_CPUID
-int main()
-{
- int a = 0;
- __asm {
- xor EAX, EAX;
- cpuid;
- mov a, EAX;
- }
-
- return a;
-}
-#endif
-
#ifdef TEST_KWSYS_STL_HAS_WSTRING
# include <string>
void f(std::wstring*)
#include <iostream>
#include <vector>
-#include <stddef.h> /* size_t */
-#include <string.h> /* strcmp */
+#include <cstddef> /* size_t */
+#include <cstring> /* strcmp */
static void* random_ptr = reinterpret_cast<void*>(0x123);
#include <iostream>
#include <vector>
-#include <assert.h> /* assert */
-#include <string.h> /* strcmp */
+#include <cassert> /* assert */
+#include <cstring> /* strcmp */
int testCommandLineArguments1(int argc, char* argv[])
{
std::cout << "Value of N: " << n << std::endl;
std::cout << "Value of M: " << m << std::endl;
std::cout << "Value of P: " << p << std::endl;
- if (m) {
- delete[] m;
- }
+ delete[] m;
char** newArgv = nullptr;
int newArgc = 0;
Directory testdir;
// Set res to failure if the directory doesn't load
- res += !testdir.Load(testdirpath);
+ std::string errorMessage = "";
+ res += !testdir.Load(testdirpath, &errorMessage);
+ if (errorMessage != "") {
+ std::cerr << "Failed to list directory: " << errorMessage << std::endl;
+ }
// Increment res failure if the directory appears empty
res += testdir.GetNumberOfFiles() == 0;
// Increment res failures if the path has changed from
return res;
}
+int _nonExistentDirectoryTest()
+{
+ using namespace kwsys;
+ int res = 0;
+ std::string testdirpath(TEST_SYSTEMTOOLS_BINARY_DIR
+ "/directory_testing/doesnt_exist/");
+ std::string errorMessage;
+ Directory testdir;
+
+ errorMessage = "foo";
+ // Increment res failure if directory lists
+ res += testdir.Load(testdirpath, &errorMessage);
+#if !defined(_WIN32) || defined(__CYGWIN__)
+ // Increment res failure if errorMessage is unmodified
+ res += (errorMessage == "foo");
+#endif
+
+ errorMessage = "foo";
+ // Increment res failure if directory has files
+ res += (testdir.GetNumberOfFilesInDirectory(testdirpath, &errorMessage) > 0);
+#if !defined(_WIN32) || defined(__CYGWIN__)
+ // Increment res failure if errorMessage is unmodified
+ res += (errorMessage == "foo");
+#endif
+
+ return res;
+}
+
int _copyDirectoryTest()
{
using namespace kwsys;
int testDirectory(int, char* [])
{
- return _doLongPathTest() + _copyDirectoryTest();
+ return _doLongPathTest() + _nonExistentDirectoryTest() +
+ _copyDirectoryTest();
}
DL_EXPORT int TestDynamicLoaderData = 0;
-DL_EXPORT void TestDynamicLoaderSymbolPointer()
+DL_EXPORT void TestDynamicLoaderSymbolPointer(void)
{
}
#include KWSYS_HEADER(Encoding.h)
#include <algorithm>
+#include <clocale>
+#include <cstdlib>
+#include <cstring>
#include <iostream>
-#include <locale.h>
-#include <stdlib.h>
-#include <string.h>
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
std::string str2 = kwsys::Encoding::ToNarrow(wstr);
wchar_t* c_wstr = kwsysEncoding_DupToWide(str.c_str());
char* c_str2 = kwsysEncoding_DupToNarrow(c_wstr);
- if (!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str()))) {
+ if (!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str()) != 0)) {
std::cout << "converted string was different: " << str2 << std::endl;
std::cout << "converted string was different: " << c_str2 << std::endl;
ret++;
#endif
#include KWSYS_HEADER(FStream.hxx)
-#include <string.h>
-#ifdef __BORLANDC__
-# include <mem.h> /* memcmp */
-#endif
+#include <cstring>
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
return 0;
}
+static int testBOMIO()
+{
+ // test various encodings in binary mode
+ for (int i = 0; i < num_test_files; i++) {
+ kwsys::fstream f("bomio.txt",
+ kwsys::fstream::in | kwsys::fstream::out |
+ kwsys::fstream::binary | kwsys::fstream::trunc);
+ f.write(reinterpret_cast<const char*>(expected_bom_data[i] + 1),
+ *expected_bom_data[i]);
+ f.write(reinterpret_cast<const char*>(file_data[i] + 1), file_data[i][0]);
+ if (!f.good()) {
+ std::cout << "Unable to write data " << i << std::endl;
+ return 1;
+ }
+ f.seekp(0);
+
+ kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(f);
+ if (bom != expected_bom[i]) {
+ std::cout << "Unexpected BOM " << i << std::endl;
+ return 1;
+ }
+ char data[max_test_file_size];
+ f.read(data, file_data[i][0]);
+ if (!f.good()) {
+ std::cout << "Unable to read data " << i << std::endl;
+ return 1;
+ }
+
+ if (memcmp(data, file_data[i] + 1, file_data[i][0]) != 0) {
+ std::cout << "Incorrect read data " << i << std::endl;
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
int testFStream(int, char* [])
{
int ret = 0;
ret |= testNoFile();
ret |= testBOM();
+ ret |= testBOMIO();
return ret;
}
+++ /dev/null
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-#include "kwsysPrivate.h"
-#include KWSYS_HEADER(hash_map.hxx)
-#include KWSYS_HEADER(hash_set.hxx)
-
-// Work-around CMake dependency scanning limitation. This must
-// duplicate the above list of headers.
-#if 0
-# include "hash_map.hxx.in"
-# include "hash_set.hxx.in"
-#endif
-
-#include <iostream>
-
-#if defined(_MSC_VER)
-# pragma warning(disable : 4786)
-#endif
-
-#if defined(__sgi) && !defined(__GNUC__)
-# pragma set woff 1468 /* inline function cannot be explicitly instantiated \
- */
-#endif
-
-template class kwsys::hash_map<const char*, int>;
-template class kwsys::hash_set<int>;
-
-static bool test_hash_map()
-{
- using mtype = kwsys::hash_map<const char*, int>;
- mtype m;
- const char* keys[] = { "hello", "world" };
- m[keys[0]] = 1;
- m.insert(mtype::value_type(keys[1], 2));
- int sum = 0;
- for (auto& mi : m) {
- std::cout << "Found entry [" << mi.first << "," << mi.second << "]"
- << std::endl;
- sum += mi.second;
- }
- return sum == 3;
-}
-
-static bool test_hash_set()
-{
- using stype = kwsys::hash_set<int>;
- stype s;
- s.insert(1);
- s.insert(2);
- int sum = 0;
- for (int si : s) {
- std::cout << "Found entry [" << si << "]" << std::endl;
- sum += si;
- }
- return sum == 3;
-}
-
-int testHashSTL(int, char* [])
-{
- bool result = true;
- result = test_hash_map() && result;
- result = test_hash_set() && result;
- return result ? 0 : 1;
-}
# include <unistd.h>
#endif
-#if defined(__BORLANDC__)
-# pragma warn - 8060 /* possibly incorrect assignment */
-#endif
-
/* Platform-specific sleep functions. */
#if defined(__BEOS__) && !defined(__ZETA__)
printf("The process is still executing.\n");
break;
case kwsysProcess_State_Expired:
- printf("Child was killed when timeout expired.\n");
+ printf("Subprocess was killed when timeout expired.\n");
break;
case kwsysProcess_State_Exited:
- printf("Child exited with value = %d\n", kwsysProcess_GetExitValue(kp));
+ printf("Subprocess exited with value = %d\n",
+ kwsysProcess_GetExitValue(kp));
result = ((exception != kwsysProcess_GetExitException(kp)) ||
(value != kwsysProcess_GetExitValue(kp)));
break;
case kwsysProcess_State_Killed:
- printf("Child was killed by parent.\n");
+ printf("Subprocess was killed by parent.\n");
break;
case kwsysProcess_State_Exception:
- printf("Child terminated abnormally: %s\n",
+ printf("Subprocess terminated abnormally: %s\n",
kwsysProcess_GetExceptionString(kp));
result = ((exception != kwsysProcess_GetExitException(kp)) ||
(value != kwsysProcess_GetExitValue(kp)));
break;
case kwsysProcess_State_Disowned:
- printf("Child was disowned.\n");
+ printf("Subprocess was disowned.\n");
break;
case kwsysProcess_State_Error:
printf("Error in administrating child process: [%s]\n",
}
fprintf(stderr, "Invalid test number %d.\n", n);
return 1;
- } else if (n >= 1 && n <= 10) {
+ }
+ if (n >= 1 && n <= 10) {
/* This is the parent process for a requested test number. */
int states[10] = {
kwsysProcess_State_Exited, kwsysProcess_State_Exited,
free(argv0);
#endif
return r;
- } else if (argc > 2 && strcmp(argv[1], "0") == 0) {
+ }
+ if (argc > 2 && strcmp(argv[1], "0") == 0) {
/* This is the special debugging test to run a given command
line. */
const char** cmd = argv + 2;
int r =
runChild(cmd, state, exception, value, 0, 1, 0, timeout, 0, 1, 0, 0, 0);
return r;
- } else {
- /* Improper usage. */
- fprintf(stdout, "Usage: %s <test number>\n", argv[0]);
- return 1;
}
+ /* Improper usage. */
+ fprintf(stdout, "Usage: %s <test number>\n", argv[0]);
+ return 1;
}
#include <iostream>
-#if defined(KWSYS_USE_LONG_LONG)
-# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)x)
-# endif
-#elif defined(KWSYS_USE___INT64)
-# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
-# define iostreamLongLong(x) (x)
-# else
-# define iostreamLongLong(x) ((long)x)
-# endif
-#else
-# error "No Long Long"
-#endif
-
#define printMethod(info, m) std::cout << #m << ": " << info.m() << "\n"
#define printMethod2(info, m, unit) \
std::cout << #m << ": " << info.m() << " " << unit << "\n"
#define printMethod3(info, m, unit) \
- std::cout << #m << ": " << iostreamLongLong(info.m) << " " << unit << "\n"
+ std::cout << #m << ": " << info.m << " " << unit << "\n"
int testSystemInformation(int, char* [])
{
// left on disk.
#include <testSystemTools.h>
+#include <cstdlib> /* free */
+#include <cstring> /* strcmp */
#include <iostream>
#include <sstream>
-#include <stdlib.h> /* free */
-#include <string.h> /* strcmp */
#if defined(_WIN32) && !defined(__CYGWIN__)
-# include <io.h> /* _umask (MSVC) / umask (Borland) */
+# include <io.h> /* _umask (MSVC) */
# ifdef _MSC_VER
-# define umask _umask // Note this is still umask on Borland
+# define umask _umask
# endif
#endif
#include <sys/stat.h> /* umask (POSIX), _S_I* constants (Windows) */
-// Visual C++ does not define mode_t (note that Borland does, however).
+// Visual C++ does not define mode_t.
#if defined(_MSC_VER)
typedef unsigned short mode_t;
#endif
}
// While we're at it, check proper TestFileAccess functionality.
- if (kwsys::SystemTools::TestFileAccess(testNewFile,
+ bool do_write_test = true;
+#if defined(__linux__)
+ // If we are running as root on linux ignore this check, as
+ // root can always write to files
+ do_write_test = (getuid() != 0);
+#endif
+ if (do_write_test &&
+ kwsys::SystemTools::TestFileAccess(testNewFile,
kwsys::TEST_FILE_WRITE)) {
std::cerr
<< "TestFileAccess incorrectly indicated that this is a writable file:"
res = false;
}
+#if !defined(_WIN32)
+ std::string const testBadSymlink(testNewDir + "/badSymlink.txt");
+ std::string const testBadSymlinkTgt(testNewDir + "/missing/symlinkTgt.txt");
+ if (!kwsys::SystemTools::CreateSymlink(testBadSymlinkTgt, testBadSymlink)) {
+ std::cerr << "Problem with CreateSymlink for: " << testBadSymlink << " -> "
+ << testBadSymlinkTgt << std::endl;
+ res = false;
+ }
+
+ if (!kwsys::SystemTools::Touch(testBadSymlink, false)) {
+ std::cerr << "Problem with Touch (no create) for: " << testBadSymlink
+ << std::endl;
+ res = false;
+ }
+#endif
+
+ if (!kwsys::SystemTools::Touch(testNewDir, false)) {
+ std::cerr << "Problem with Touch (no create) for: " << testNewDir
+ << std::endl;
+ res = false;
+ }
+
kwsys::SystemTools::Touch(testNewFile, true);
if (!kwsys::SystemTools::RemoveADirectory(testNewDir)) {
std::cerr << "Problem with RemoveADirectory for: " << testNewDir
char* cres =
kwsys::SystemTools::AppendStrings("Mary Had A", " Little Lamb.");
- if (strcmp(cres, "Mary Had A Little Lamb.")) {
+ if (strcmp(cres, "Mary Had A Little Lamb.") != 0) {
std::cerr << "Problem with AppendStrings "
<< "\"Mary Had A\" \" Little Lamb.\"" << std::endl;
res = false;
delete[] cres;
cres = kwsys::SystemTools::AppendStrings("Mary Had", " A ", "Little Lamb.");
- if (strcmp(cres, "Mary Had A Little Lamb.")) {
+ if (strcmp(cres, "Mary Had A Little Lamb.") != 0) {
std::cerr << "Problem with AppendStrings "
<< "\"Mary Had\" \" A \" \"Little Lamb.\"" << std::endl;
res = false;
}
cres = kwsys::SystemTools::RemoveChars("Mary Had A Little Lamb.", "aeiou");
- if (strcmp(cres, "Mry Hd A Lttl Lmb.")) {
+ if (strcmp(cres, "Mry Hd A Lttl Lmb.") != 0) {
std::cerr << "Problem with RemoveChars "
<< "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
delete[] cres;
cres = kwsys::SystemTools::RemoveCharsButUpperHex("Mary Had A Little Lamb.");
- if (strcmp(cres, "A")) {
+ if (strcmp(cres, "A") != 0) {
std::cerr << "Problem with RemoveCharsButUpperHex "
<< "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
char* cres2 = strdup("Mary Had A Little Lamb.");
kwsys::SystemTools::ReplaceChars(cres2, "aeiou", 'X');
- if (strcmp(cres2, "MXry HXd A LXttlX LXmb.")) {
+ if (strcmp(cres2, "MXry HXd A LXttlX LXmb.") != 0) {
std::cerr << "Problem with ReplaceChars "
<< "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
}
cres = kwsys::SystemTools::DuplicateString("Mary Had A Little Lamb.");
- if (strcmp(cres, "Mary Had A Little Lamb.")) {
+ if (strcmp(cres, "Mary Had A Little Lamb.") != 0) {
std::cerr << "Problem with DuplicateString "
<< "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
return ret;
}
+static bool CheckSplitString()
+{
+ bool ret = true;
+
+ auto check_split = [](std::string const& input,
+ std::initializer_list<const char*> expected) -> bool {
+ auto const components = kwsys::SystemTools::SplitString(input, '/');
+ if (components.size() != expected.size()) {
+ std::cerr << "Incorrect split count for " << input << ": "
+ << components.size() << std::endl;
+ return false;
+ }
+ size_t i = 0;
+ for (auto& part : expected) {
+ if (components[i] != part) {
+ std::cerr << "Incorrect split component " << i << " for " << input
+ << ": " << components[i] << std::endl;
+ return false;
+ }
+ ++i;
+ }
+ return true;
+ };
+
+ // No separators
+ ret &= check_split("nosep", { "nosep" });
+ // Simple
+ ret &= check_split("first/second", { "first", "second" });
+ // Separator at beginning
+ ret &= check_split("/starts/sep", { "", "starts", "sep" });
+ // Separator at end
+ ret &= check_split("ends/sep/", { "ends", "sep", "" });
+
+ return ret;
+}
+
int testSystemTools(int, char* [])
{
bool res = true;
res &= CheckURLParsing();
+ res &= CheckSplitString();
+
return res ? 0 : 1;
}
INTERFACE
MPICH_SKIP_MPICXX
OMPI_SKIP_MPICXX
+ MPI_NO_CPPBIND
_MPICC_H)
if (APPLE AND TARGET MPI::MPI_C)
#define _vtk_mpi_ibm
#endif
+// Skip SGI MPT's C++ support.
+#ifndef MPI_NO_CPPBIND
+#define MPI_NO_CPPBIND
+#define _vtk_mpi_sgi
+#endif
+
// Include the MPI header.
#include <mpi.h>
#undef _MPICC_H
#undef _vtk_mpi_ibm
#endif
+
+#ifdef _vtk_mpi_sgi
+#undef MPI_NO_CPPBIND
+#undef _vtk_mpi_sgi
+#endif
for urlbase in $urlbases; do
url="$( echo "$urlbase" | sed -e "s/ALGO/$algo/;s/HASH/$hash/" )"
- if wget "$url" -O "$temppath" >&2; then
+ if wget --no-verbose "$url" -O "$temppath" >&2; then
mv "$temppath" "$path"
return
else
PySys_SetArgvEx(0, nullptr, 0);
#ifdef VTK_PYTHON_FULL_THREADSAFE
+#if PY_VERSION_HEX < 0x03090000
+ // In Python 3.9 and higher, PyEval_ThreadsInitialized() and
+ // PyEval_InitThreads() are deprecated and do nothing.
+ // GIL initialization is handled by Py_InitializeEx().
int threadInit = PyEval_ThreadsInitialized();
if (!threadInit)
{
PyEval_InitThreads(); // initialize and acquire GIL
}
+#endif
// Always release GIL, as it has been acquired either by PyEval_InitThreads
// prior to Python 3.7 or by Py_InitializeEx in Python 3.7 and after
PyEval_SaveThread();
def get_vtk_array_type(numpy_array_type):
"""Returns a VTK typecode given a numpy array."""
# This is a Mapping from numpy array types to VTK array types.
- _np_vtk = {numpy.character:vtkConstants.VTK_UNSIGNED_CHAR,
- numpy.uint8:vtkConstants.VTK_UNSIGNED_CHAR,
+ _np_vtk = {numpy.uint8:vtkConstants.VTK_UNSIGNED_CHAR,
numpy.uint16:vtkConstants.VTK_UNSIGNED_SHORT,
numpy.uint32:vtkConstants.VTK_UNSIGNED_INT,
numpy.uint64:vtkConstants.VTK_UNSIGNED_LONG_LONG,
if (func)
{
- result = PyEval_CallObjectWithKeywords(func, args, kwds);
+ result = PyObject_Call(func, args, kwds);
Py_DECREF(func);
}
arglist = Py_BuildValue("(Ns)", obj2, eventname);
}
- PyObject* result = PyEval_CallObject(this->obj, arglist);
+ PyObject* result = PyObject_Call(this->obj, arglist, nullptr);
Py_DECREF(arglist);
if (result)
if (obj)
{
PyObject* arglist = Py_BuildValue("()");
- PyObject* result = PyEval_CallObject(obj, arglist);
+ PyObject* result = PyObject_Call(obj, arglist, nullptr);
Py_DECREF(arglist);
Py_DECREF(obj);
if (result == nullptr)
arglist = Py_BuildValue("()");
- result = PyEval_CallObject(func, arglist);
+ result = PyObject_Call(func, arglist, nullptr);
Py_DECREF(arglist);
if (result)